diff --git a/packages/google-ads-marketingplatform-admin/.flake8 b/packages/google-ads-marketingplatform-admin/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-ads-marketingplatform-admin/.flake8
+++ b/packages/google-ads-marketingplatform-admin/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-ads-marketingplatform-admin/CONTRIBUTING.rst b/packages/google-ads-marketingplatform-admin/CONTRIBUTING.rst
index a7223a5e0b19..336b66c4febd 100644
--- a/packages/google-ads-marketingplatform-admin/CONTRIBUTING.rst
+++ b/packages/google-ads-marketingplatform-admin/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-ads-marketingplatform-admin/MANIFEST.in b/packages/google-ads-marketingplatform-admin/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-ads-marketingplatform-admin/MANIFEST.in
+++ b/packages/google-ads-marketingplatform-admin/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-ads-marketingplatform-admin/docs/conf.py b/packages/google-ads-marketingplatform-admin/docs/conf.py
index 5c68a3e1a72f..046bc61ef84f 100644
--- a/packages/google-ads-marketingplatform-admin/docs/conf.py
+++ b/packages/google-ads-marketingplatform-admin/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py
index 04dda98b515d..ed52685f96f3 100644
--- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py
+++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-ads-marketingplatform-admin/noxfile.py b/packages/google-ads-marketingplatform-admin/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-ads-marketingplatform-admin/noxfile.py
+++ b/packages/google-ads-marketingplatform-admin/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-ads-marketingplatform-admin/scripts/decrypt-secrets.sh b/packages/google-ads-marketingplatform-admin/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-ads-marketingplatform-admin/scripts/decrypt-secrets.sh
+++ b/packages/google-ads-marketingplatform-admin/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-ads-marketingplatform-admin/setup.py b/packages/google-ads-marketingplatform-admin/setup.py
index 1f5b7d1d66ee..7965e7b2a15f 100644
--- a/packages/google-ads-marketingplatform-admin/setup.py
+++ b/packages/google-ads-marketingplatform-admin/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-ads-marketingplatform-admin/testing/constraints-3.13.txt b/packages/google-ads-marketingplatform-admin/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-ads-marketingplatform-admin/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-artifact-registry/.flake8 b/packages/google-cloud-artifact-registry/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-artifact-registry/.flake8
+++ b/packages/google-cloud-artifact-registry/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-artifact-registry/CONTRIBUTING.rst b/packages/google-cloud-artifact-registry/CONTRIBUTING.rst
index bba85a629922..aa2527b71531 100644
--- a/packages/google-cloud-artifact-registry/CONTRIBUTING.rst
+++ b/packages/google-cloud-artifact-registry/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-artifact-registry/MANIFEST.in b/packages/google-cloud-artifact-registry/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-artifact-registry/MANIFEST.in
+++ b/packages/google-cloud-artifact-registry/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-artifact-registry/docs/conf.py b/packages/google-cloud-artifact-registry/docs/conf.py
index 253a01b6b769..986a56405770 100644
--- a/packages/google-cloud-artifact-registry/docs/conf.py
+++ b/packages/google-cloud-artifact-registry/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/rest.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/rest.py
index 042d6dc31ce5..3189527330cd 100644
--- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/rest.py
+++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/rest.py
@@ -55,7 +55,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/services/artifact_registry/transports/rest.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/services/artifact_registry/transports/rest.py
index 3616541c918f..3e2aef45dc6d 100644
--- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/services/artifact_registry/transports/rest.py
+++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/services/artifact_registry/transports/rest.py
@@ -52,7 +52,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-artifact-registry/noxfile.py b/packages/google-cloud-artifact-registry/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-artifact-registry/noxfile.py
+++ b/packages/google-cloud-artifact-registry/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-artifact-registry/scripts/decrypt-secrets.sh b/packages/google-cloud-artifact-registry/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-artifact-registry/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-artifact-registry/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-artifact-registry/setup.py b/packages/google-cloud-artifact-registry/setup.py
index f104ca4b57a3..d6c003064d1a 100644
--- a/packages/google-cloud-artifact-registry/setup.py
+++ b/packages/google-cloud-artifact-registry/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -85,6 +86,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-artifact-registry/testing/constraints-3.13.txt b/packages/google-cloud-artifact-registry/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-artifact-registry/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-build/.flake8 b/packages/google-cloud-build/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-build/.flake8
+++ b/packages/google-cloud-build/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-build/CONTRIBUTING.rst b/packages/google-cloud-build/CONTRIBUTING.rst
index 5fa4e56c6776..71b753d4b82a 100644
--- a/packages/google-cloud-build/CONTRIBUTING.rst
+++ b/packages/google-cloud-build/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-build/MANIFEST.in b/packages/google-cloud-build/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-build/MANIFEST.in
+++ b/packages/google-cloud-build/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-build/docs/conf.py b/packages/google-cloud-build/docs/conf.py
index cc107bc88d72..ae0ac9f9251f 100644
--- a/packages/google-cloud-build/docs/conf.py
+++ b/packages/google-cloud-build/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/services/cloud_build/transports/rest.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/services/cloud_build/transports/rest.py
index b93227d42658..7f031fcc783a 100644
--- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/services/cloud_build/transports/rest.py
+++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/services/cloud_build/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/services/repository_manager/transports/rest.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/services/repository_manager/transports/rest.py
index b93405adc868..3f0ef24c8b88 100644
--- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/services/repository_manager/transports/rest.py
+++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/services/repository_manager/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-build/noxfile.py b/packages/google-cloud-build/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-build/noxfile.py
+++ b/packages/google-cloud-build/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-build/scripts/decrypt-secrets.sh b/packages/google-cloud-build/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-build/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-build/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-build/setup.py b/packages/google-cloud-build/setup.py
index e4025c800607..37170fe4b3b3 100644
--- a/packages/google-cloud-build/setup.py
+++ b/packages/google-cloud-build/setup.py
@@ -47,6 +47,7 @@
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"grpc-google-iam-v1 >=0.12.4, <1.0.0dev",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -85,6 +86,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-build/testing/constraints-3.13.txt b/packages/google-cloud-build/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-build/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-container/.flake8 b/packages/google-cloud-container/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-container/.flake8
+++ b/packages/google-cloud-container/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-container/CONTRIBUTING.rst b/packages/google-cloud-container/CONTRIBUTING.rst
index 19d8e6cbe595..03ffb8038602 100644
--- a/packages/google-cloud-container/CONTRIBUTING.rst
+++ b/packages/google-cloud-container/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-container/MANIFEST.in b/packages/google-cloud-container/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-container/MANIFEST.in
+++ b/packages/google-cloud-container/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-container/docs/conf.py b/packages/google-cloud-container/docs/conf.py
index 288c5268c208..6f4bf2594440 100644
--- a/packages/google-cloud-container/docs/conf.py
+++ b/packages/google-cloud-container/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py
index f6b068df57bc..043cddf6ba31 100644
--- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py
+++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py
@@ -42,7 +42,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-container/noxfile.py b/packages/google-cloud-container/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-container/noxfile.py
+++ b/packages/google-cloud-container/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-container/scripts/decrypt-secrets.sh b/packages/google-cloud-container/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-container/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-container/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-container/setup.py b/packages/google-cloud-container/setup.py
index 14d3dd789cd7..19dc890298c2 100644
--- a/packages/google-cloud-container/setup.py
+++ b/packages/google-cloud-container/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -82,6 +83,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-container/testing/constraints-3.13.txt b/packages/google-cloud-container/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-container/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-containeranalysis/.flake8 b/packages/google-cloud-containeranalysis/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-containeranalysis/.flake8
+++ b/packages/google-cloud-containeranalysis/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-containeranalysis/CONTRIBUTING.rst b/packages/google-cloud-containeranalysis/CONTRIBUTING.rst
index 711a985795b9..b222705428a5 100644
--- a/packages/google-cloud-containeranalysis/CONTRIBUTING.rst
+++ b/packages/google-cloud-containeranalysis/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-containeranalysis/MANIFEST.in b/packages/google-cloud-containeranalysis/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-containeranalysis/MANIFEST.in
+++ b/packages/google-cloud-containeranalysis/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-containeranalysis/docs/conf.py b/packages/google-cloud-containeranalysis/docs/conf.py
index 993d5ce5651a..25a960a36d7d 100644
--- a/packages/google-cloud-containeranalysis/docs/conf.py
+++ b/packages/google-cloud-containeranalysis/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/rest.py b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/rest.py
index 53dd89f6c3b4..0d99753fe5a7 100644
--- a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/rest.py
+++ b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-containeranalysis/noxfile.py b/packages/google-cloud-containeranalysis/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-containeranalysis/noxfile.py
+++ b/packages/google-cloud-containeranalysis/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-containeranalysis/scripts/decrypt-secrets.sh b/packages/google-cloud-containeranalysis/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-containeranalysis/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-containeranalysis/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-containeranalysis/setup.py b/packages/google-cloud-containeranalysis/setup.py
index 6b7abef7cb9f..4bf537f9f883 100644
--- a/packages/google-cloud-containeranalysis/setup.py
+++ b/packages/google-cloud-containeranalysis/setup.py
@@ -49,6 +49,7 @@
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"grafeas >=1.4.1, <2.0dev",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -88,6 +89,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-containeranalysis/testing/constraints-3.13.txt b/packages/google-cloud-containeranalysis/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-containeranalysis/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-dataflow-client/.flake8 b/packages/google-cloud-dataflow-client/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-dataflow-client/.flake8
+++ b/packages/google-cloud-dataflow-client/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataflow-client/CONTRIBUTING.rst b/packages/google-cloud-dataflow-client/CONTRIBUTING.rst
index e4180d248648..711a1f1de3d2 100644
--- a/packages/google-cloud-dataflow-client/CONTRIBUTING.rst
+++ b/packages/google-cloud-dataflow-client/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-dataflow-client/MANIFEST.in b/packages/google-cloud-dataflow-client/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-dataflow-client/MANIFEST.in
+++ b/packages/google-cloud-dataflow-client/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataflow-client/docs/conf.py b/packages/google-cloud-dataflow-client/docs/conf.py
index 81bbee55d09c..64a6dfac2f31 100644
--- a/packages/google-cloud-dataflow-client/docs/conf.py
+++ b/packages/google-cloud-dataflow-client/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/flex_templates_service/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/flex_templates_service/transports/rest.py
index f97058047900..a365f1aebefd 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/flex_templates_service/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/flex_templates_service/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/jobs_v1_beta3/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/jobs_v1_beta3/transports/rest.py
index 96567039de54..cde562b8472d 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/jobs_v1_beta3/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/jobs_v1_beta3/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/messages_v1_beta3/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/messages_v1_beta3/transports/rest.py
index 7ccec9c2c9dd..25c865ba3506 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/messages_v1_beta3/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/messages_v1_beta3/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/metrics_v1_beta3/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/metrics_v1_beta3/transports/rest.py
index 2876620c8881..1d82331355e1 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/metrics_v1_beta3/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/metrics_v1_beta3/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/snapshots_v1_beta3/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/snapshots_v1_beta3/transports/rest.py
index 15c87c232705..da01f5013a7a 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/snapshots_v1_beta3/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/snapshots_v1_beta3/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/templates_service/transports/rest.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/templates_service/transports/rest.py
index 89c25a0dc3cf..a72928ddda61 100644
--- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/templates_service/transports/rest.py
+++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/services/templates_service/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataflow-client/noxfile.py b/packages/google-cloud-dataflow-client/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-dataflow-client/noxfile.py
+++ b/packages/google-cloud-dataflow-client/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-dataflow-client/scripts/decrypt-secrets.sh b/packages/google-cloud-dataflow-client/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-dataflow-client/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-dataflow-client/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-dataflow-client/setup.py b/packages/google-cloud-dataflow-client/setup.py
index 2d7f9d5c4d67..b6f30f39b52b 100644
--- a/packages/google-cloud-dataflow-client/setup.py
+++ b/packages/google-cloud-dataflow-client/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -82,6 +83,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-dataflow-client/testing/constraints-3.13.txt b/packages/google-cloud-dataflow-client/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-dataflow-client/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-dataproc-metastore/.flake8 b/packages/google-cloud-dataproc-metastore/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-dataproc-metastore/.flake8
+++ b/packages/google-cloud-dataproc-metastore/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataproc-metastore/CONTRIBUTING.rst b/packages/google-cloud-dataproc-metastore/CONTRIBUTING.rst
index e0e6cb3fa536..6fe1af8b6542 100644
--- a/packages/google-cloud-dataproc-metastore/CONTRIBUTING.rst
+++ b/packages/google-cloud-dataproc-metastore/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-dataproc-metastore/MANIFEST.in b/packages/google-cloud-dataproc-metastore/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-dataproc-metastore/MANIFEST.in
+++ b/packages/google-cloud-dataproc-metastore/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataproc-metastore/docs/conf.py b/packages/google-cloud-dataproc-metastore/docs/conf.py
index 56bf5ae24b46..848cd0332bc3 100644
--- a/packages/google-cloud-dataproc-metastore/docs/conf.py
+++ b/packages/google-cloud-dataproc-metastore/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py
index 51c5d973bd8a..482a4af3470c 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py
index 78669328d64b..cc7e3d68b01b 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/services/dataproc_metastore_federation/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py
index 9a2e188375a8..32b60dc42537 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py
index a2fa1b11f8a1..1fc42adf0763 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/services/dataproc_metastore_federation/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py
index c44df896cca8..8688be204a6f 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py
index e6eff5afaf83..6d07391a9667 100644
--- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py
+++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/services/dataproc_metastore_federation/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dataproc-metastore/noxfile.py b/packages/google-cloud-dataproc-metastore/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-dataproc-metastore/noxfile.py
+++ b/packages/google-cloud-dataproc-metastore/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-dataproc-metastore/scripts/decrypt-secrets.sh b/packages/google-cloud-dataproc-metastore/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-dataproc-metastore/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-dataproc-metastore/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-dataproc-metastore/setup.py b/packages/google-cloud-dataproc-metastore/setup.py
index f6bfb2d7af39..c3ae21177f4f 100644
--- a/packages/google-cloud-dataproc-metastore/setup.py
+++ b/packages/google-cloud-dataproc-metastore/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -83,6 +84,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-dataproc-metastore/testing/constraints-3.13.txt b/packages/google-cloud-dataproc-metastore/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-dataproc-metastore/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-dialogflow-cx/.flake8 b/packages/google-cloud-dialogflow-cx/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-dialogflow-cx/.flake8
+++ b/packages/google-cloud-dialogflow-cx/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dialogflow-cx/CONTRIBUTING.rst b/packages/google-cloud-dialogflow-cx/CONTRIBUTING.rst
index df4bcb495c6b..078f2b09c150 100644
--- a/packages/google-cloud-dialogflow-cx/CONTRIBUTING.rst
+++ b/packages/google-cloud-dialogflow-cx/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-dialogflow-cx/MANIFEST.in b/packages/google-cloud-dialogflow-cx/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-dialogflow-cx/MANIFEST.in
+++ b/packages/google-cloud-dialogflow-cx/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dialogflow-cx/docs/conf.py b/packages/google-cloud-dialogflow-cx/docs/conf.py
index af586c43f007..0e9429f6a3b1 100644
--- a/packages/google-cloud-dialogflow-cx/docs/conf.py
+++ b/packages/google-cloud-dialogflow-cx/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py
index 0c87c2570203..66271abe558b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/changelogs/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/changelogs/transports/rest.py
index 33d2a0f6d6a9..aabbc6951431 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/changelogs/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/changelogs/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/deployments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/deployments/transports/rest.py
index 12886a2554e3..5a836f40914b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/deployments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/deployments/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/entity_types/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/entity_types/transports/rest.py
index 1a52588f4486..c88cbfa0bfd5 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/entity_types/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/entity_types/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/transports/rest.py
index 6cdce3bf9b42..4868f8dd8422 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/experiments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/experiments/transports/rest.py
index 851ec4eed651..ff62c2b65700 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/experiments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/experiments/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/transports/rest.py
index c5324190a2fb..5c98c5579822 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/transports/rest.py
index fca2235fb1da..cc9ab8afffe8 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/intents/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/intents/transports/rest.py
index 471b45a79f42..24f532b86831 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/intents/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/intents/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/transports/rest.py
index 2431778b7752..cd79ac178da2 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/rest.py
index 79d588762645..cde44d062170 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/rest.py
index 03f39891ce17..c1ac168d5b45 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/transports/rest.py
index c00d723312ca..4fc22f213607 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/transports/rest.py
index b23da6f889dc..276cf60d76af 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/rest.py
index 9d9a42b6a054..56a2c1ecf3d8 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/versions/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/versions/transports/rest.py
index 4338a7c98473..f4c92453b7fc 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/versions/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/versions/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/transports/rest.py
index 7937e1e592bd..e62fa83aabfe 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py
index 09a197289436..bb8c2f9ee711 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -220,7 +221,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = AgentsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(AgentsClient).get_transport_class, type(AgentsClient)
+ )
def __init__(
self,
@@ -402,8 +405,6 @@ async def sample_list_agents():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1594,7 +1595,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1647,7 +1652,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1703,7 +1712,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1753,7 +1766,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1806,7 +1823,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/client.py
index 946561cbe551..7d49fad60a1b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/client.py
@@ -835,7 +835,7 @@ def __init__(
transport_init: Union[
Type[AgentsTransport], Callable[..., AgentsTransport]
] = (
- AgentsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., AgentsTransport], transport)
)
@@ -963,8 +963,6 @@ def sample_list_agents():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -2145,7 +2143,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2198,7 +2200,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2254,7 +2260,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2304,7 +2314,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2357,7 +2371,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py
index 5a9a05ac6566..dc3a93232dd5 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import agent
@@ -65,8 +51,6 @@ def __init__(
request: agent.ListAgentsRequest,
response: agent.ListAgentsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = agent.ListAgentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[agent.ListAgentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[agent.Agent]:
@@ -139,8 +113,6 @@ def __init__(
request: agent.ListAgentsRequest,
response: agent.ListAgentsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = agent.ListAgentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[agent.ListAgentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[agent.Agent]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py
index 7c90d49ce258..029a78215c93 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py
@@ -92,8 +92,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -106,7 +104,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -203,31 +201,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py
index 7deb090d121b..8633c90f1cf4 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py
@@ -131,8 +131,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py
index df1a928adf73..9f383e9107ed 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -179,8 +178,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -237,9 +235,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -604,17 +599,17 @@ def update_generative_settings(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_agents: self._wrap_method(
+ self.list_agents: gapic_v1.method_async.wrap_method(
self.list_agents,
default_timeout=None,
client_info=client_info,
),
- self.get_agent: self._wrap_method(
+ self.get_agent: gapic_v1.method_async.wrap_method(
self.get_agent,
default_timeout=None,
client_info=client_info,
),
- self.create_agent: self._wrap_method(
+ self.create_agent: gapic_v1.method_async.wrap_method(
self.create_agent,
default_retry=retries.AsyncRetry(
initial=0.1,
@@ -628,85 +623,51 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=180.0,
client_info=client_info,
),
- self.update_agent: self._wrap_method(
+ self.update_agent: gapic_v1.method_async.wrap_method(
self.update_agent,
default_timeout=None,
client_info=client_info,
),
- self.delete_agent: self._wrap_method(
+ self.delete_agent: gapic_v1.method_async.wrap_method(
self.delete_agent,
default_timeout=None,
client_info=client_info,
),
- self.export_agent: self._wrap_method(
+ self.export_agent: gapic_v1.method_async.wrap_method(
self.export_agent,
default_timeout=None,
client_info=client_info,
),
- self.restore_agent: self._wrap_method(
+ self.restore_agent: gapic_v1.method_async.wrap_method(
self.restore_agent,
default_timeout=None,
client_info=client_info,
),
- self.validate_agent: self._wrap_method(
+ self.validate_agent: gapic_v1.method_async.wrap_method(
self.validate_agent,
default_timeout=None,
client_info=client_info,
),
- self.get_agent_validation_result: self._wrap_method(
+ self.get_agent_validation_result: gapic_v1.method_async.wrap_method(
self.get_agent_validation_result,
default_timeout=None,
client_info=client_info,
),
- self.get_generative_settings: self._wrap_method(
+ self.get_generative_settings: gapic_v1.method_async.wrap_method(
self.get_generative_settings,
default_timeout=None,
client_info=client_info,
),
- self.update_generative_settings: self._wrap_method(
+ self.update_generative_settings: gapic_v1.method_async.wrap_method(
self.update_generative_settings,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/rest.py
index e0a166fd9b86..0ca5c2ab8960 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/agents/transports/rest.py
@@ -16,20 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+
+
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
from google.cloud.dialogflowcx_v3beta1.types import (
generative_settings as gcdc_generative_settings,
)
@@ -37,14 +53,8 @@
from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent
from google.cloud.dialogflowcx_v3beta1.types import generative_settings
+from .base import AgentsTransport
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseAgentsRestTransport
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
-
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
@@ -503,8 +513,8 @@ class AgentsRestStub:
_interceptor: AgentsRestInterceptor
-class AgentsRestTransport(_BaseAgentsRestTransport):
- """REST backend synchronous transport for Agents.
+class AgentsRestTransport(AgentsTransport):
+ """REST backend transport for Agents.
Service for managing
[Agents][google.cloud.dialogflow.cx.v3beta1.Agent].
@@ -514,6 +524,7 @@ class AgentsRestTransport(_BaseAgentsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -567,12 +578,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -642,32 +662,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateAgent(_BaseAgentsRestTransport._BaseCreateAgent, AgentsRestStub):
+ class _CreateAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.CreateAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -709,34 +716,45 @@ def __call__(
"""
- http_options = _BaseAgentsRestTransport._BaseCreateAgent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*}/agents",
+ "body": "agent",
+ },
+ ]
request, metadata = self._interceptor.pre_create_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseCreateAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_agent.CreateAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseAgentsRestTransport._BaseCreateAgent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseCreateAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._CreateAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -752,31 +770,19 @@ def __call__(
resp = self._interceptor.post_create_agent(resp)
return resp
- class _DeleteAgent(_BaseAgentsRestTransport._BaseDeleteAgent, AgentsRestStub):
+ class _DeleteAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.DeleteAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -799,29 +805,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = _BaseAgentsRestTransport._BaseDeleteAgent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseDeleteAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.DeleteAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseDeleteAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._DeleteAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -829,32 +844,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _ExportAgent(_BaseAgentsRestTransport._BaseExportAgent, AgentsRestStub):
+ class _ExportAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.ExportAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -884,34 +886,45 @@ def __call__(
"""
- http_options = _BaseAgentsRestTransport._BaseExportAgent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*}:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseExportAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.ExportAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseAgentsRestTransport._BaseExportAgent._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseExportAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._ExportAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -925,31 +938,19 @@ def __call__(
resp = self._interceptor.post_export_agent(resp)
return resp
- class _GetAgent(_BaseAgentsRestTransport._BaseGetAgent, AgentsRestStub):
+ class _GetAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.GetAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -991,29 +992,38 @@ def __call__(
"""
- http_options = _BaseAgentsRestTransport._BaseGetAgent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseGetAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.GetAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseGetAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._GetAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1029,33 +1039,19 @@ def __call__(
resp = self._interceptor.post_get_agent(resp)
return resp
- class _GetAgentValidationResult(
- _BaseAgentsRestTransport._BaseGetAgentValidationResult, AgentsRestStub
- ):
+ class _GetAgentValidationResult(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.GetAgentValidationResult")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetAgentValidationResult")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1085,29 +1081,40 @@ def __call__(
"""
- http_options = (
- _BaseAgentsRestTransport._BaseGetAgentValidationResult._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/validationResult}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_agent_validation_result(
request, metadata
)
- transcoded_request = _BaseAgentsRestTransport._BaseGetAgentValidationResult._get_transcoded_request(
- http_options, request
- )
+ pb_request = agent.GetAgentValidationResultRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseAgentsRestTransport._BaseGetAgentValidationResult._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._GetAgentValidationResult._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1123,33 +1130,21 @@ def __call__(
resp = self._interceptor.post_get_agent_validation_result(resp)
return resp
- class _GetGenerativeSettings(
- _BaseAgentsRestTransport._BaseGetGenerativeSettings, AgentsRestStub
- ):
+ class _GetGenerativeSettings(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.GetGenerativeSettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetGenerativeSettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "languageCode": "",
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1177,29 +1172,40 @@ def __call__(
Settings for Generative AI.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseGetGenerativeSettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/generativeSettings}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_generative_settings(
request, metadata
)
- transcoded_request = _BaseAgentsRestTransport._BaseGetGenerativeSettings._get_transcoded_request(
- http_options, request
- )
+ pb_request = agent.GetGenerativeSettingsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseAgentsRestTransport._BaseGetGenerativeSettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._GetGenerativeSettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1215,31 +1221,19 @@ def __call__(
resp = self._interceptor.post_get_generative_settings(resp)
return resp
- class _ListAgents(_BaseAgentsRestTransport._BaseListAgents, AgentsRestStub):
+ class _ListAgents(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.ListAgents")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListAgents")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1268,29 +1262,38 @@ def __call__(
"""
- http_options = _BaseAgentsRestTransport._BaseListAgents._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*}/agents",
+ },
+ ]
request, metadata = self._interceptor.pre_list_agents(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseListAgents._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.ListAgentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseListAgents._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._ListAgents._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1306,32 +1309,19 @@ def __call__(
resp = self._interceptor.post_list_agents(resp)
return resp
- class _RestoreAgent(_BaseAgentsRestTransport._BaseRestoreAgent, AgentsRestStub):
+ class _RestoreAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.RestoreAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("RestoreAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1361,36 +1351,45 @@ def __call__(
"""
- http_options = (
- _BaseAgentsRestTransport._BaseRestoreAgent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*}:restore",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_restore_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseRestoreAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.RestoreAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseAgentsRestTransport._BaseRestoreAgent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseRestoreAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._RestoreAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1404,32 +1403,19 @@ def __call__(
resp = self._interceptor.post_restore_agent(resp)
return resp
- class _UpdateAgent(_BaseAgentsRestTransport._BaseUpdateAgent, AgentsRestStub):
+ class _UpdateAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.UpdateAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1471,34 +1457,45 @@ def __call__(
"""
- http_options = _BaseAgentsRestTransport._BaseUpdateAgent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{agent.name=projects/*/locations/*/agents/*}",
+ "body": "agent",
+ },
+ ]
request, metadata = self._interceptor.pre_update_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseUpdateAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_agent.UpdateAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseAgentsRestTransport._BaseUpdateAgent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseUpdateAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._UpdateAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1514,34 +1511,19 @@ def __call__(
resp = self._interceptor.post_update_agent(resp)
return resp
- class _UpdateGenerativeSettings(
- _BaseAgentsRestTransport._BaseUpdateGenerativeSettings, AgentsRestStub
- ):
+ class _UpdateGenerativeSettings(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.UpdateGenerativeSettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateGenerativeSettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1570,34 +1552,47 @@ def __call__(
Settings for Generative AI.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseUpdateGenerativeSettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{generative_settings.name=projects/*/locations/*/agents/*/generativeSettings}",
+ "body": "generative_settings",
+ },
+ ]
request, metadata = self._interceptor.pre_update_generative_settings(
request, metadata
)
- transcoded_request = _BaseAgentsRestTransport._BaseUpdateGenerativeSettings._get_transcoded_request(
- http_options, request
- )
+ pb_request = agent.UpdateGenerativeSettingsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseAgentsRestTransport._BaseUpdateGenerativeSettings._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseAgentsRestTransport._BaseUpdateGenerativeSettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._UpdateGenerativeSettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1613,32 +1608,19 @@ def __call__(
resp = self._interceptor.post_update_generative_settings(resp)
return resp
- class _ValidateAgent(_BaseAgentsRestTransport._BaseValidateAgent, AgentsRestStub):
+ class _ValidateAgent(AgentsRestStub):
def __hash__(self):
- return hash("AgentsRestTransport.ValidateAgent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ValidateAgent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1667,36 +1649,45 @@ def __call__(
"""
- http_options = (
- _BaseAgentsRestTransport._BaseValidateAgent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*}:validate",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_validate_agent(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseValidateAgent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = agent.ValidateAgentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseAgentsRestTransport._BaseValidateAgent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseValidateAgent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = AgentsRestTransport._ValidateAgent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1805,32 +1796,7 @@ def validate_agent(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseAgentsRestTransport._BaseGetLocation, AgentsRestStub):
- def __hash__(self):
- return hash("AgentsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(AgentsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1854,29 +1820,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = _BaseAgentsRestTransport._BaseGetLocation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = AgentsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1884,9 +1853,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1894,32 +1862,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(_BaseAgentsRestTransport._BaseListLocations, AgentsRestStub):
- def __hash__(self):
- return hash("AgentsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(AgentsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1943,31 +1886,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = AgentsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1975,9 +1919,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1985,34 +1928,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseAgentsRestTransport._BaseCancelOperation, AgentsRestStub
- ):
- def __hash__(self):
- return hash("AgentsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(AgentsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -2033,33 +1949,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = AgentsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2073,32 +1994,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseAgentsRestTransport._BaseGetOperation, AgentsRestStub):
- def __hash__(self):
- return hash("AgentsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(AgentsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -2122,31 +2018,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = AgentsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2154,9 +2055,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -2164,32 +2064,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(_BaseAgentsRestTransport._BaseListOperations, AgentsRestStub):
- def __hash__(self):
- return hash("AgentsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(AgentsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -2213,31 +2088,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseAgentsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseAgentsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseAgentsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = AgentsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2245,9 +2125,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py
index 31c1476e4a7e..4aaafa9d87c9 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -186,7 +187,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = ChangelogsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(ChangelogsClient).get_transport_class, type(ChangelogsClient)
+ )
def __init__(
self,
@@ -367,8 +370,6 @@ async def sample_list_changelogs():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -512,7 +513,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -565,7 +570,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -621,7 +630,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -671,7 +684,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -724,7 +741,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py
index 9b053e943d82..75d58ed1d3c9 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/client.py
@@ -663,7 +663,7 @@ def __init__(
transport_init: Union[
Type[ChangelogsTransport], Callable[..., ChangelogsTransport]
] = (
- ChangelogsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., ChangelogsTransport], transport)
)
@@ -790,8 +790,6 @@ def sample_list_changelogs():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -945,7 +943,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -998,7 +1000,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1054,7 +1060,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1104,7 +1114,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1157,7 +1171,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py
index b1be574e5214..7355b923e46b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import changelog
@@ -65,8 +51,6 @@ def __init__(
request: changelog.ListChangelogsRequest,
response: changelog.ListChangelogsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = changelog.ListChangelogsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[changelog.ListChangelogsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[changelog.Changelog]:
@@ -139,8 +113,6 @@ def __init__(
request: changelog.ListChangelogsRequest,
response: changelog.ListChangelogsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListChangelogsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = changelog.ListChangelogsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[changelog.ListChangelogsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[changelog.Changelog]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py
index 8982fd2e7fdf..5b06d2ce327a 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/base.py
@@ -86,8 +86,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -100,7 +98,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -143,31 +141,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py
index 9a98d6a96340..b1eb573d3e57 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc.py
@@ -124,8 +124,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py
index a6861731a38d..e468f39f9cb6 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -172,8 +171,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -230,9 +228,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -302,55 +297,21 @@ def get_changelog(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_changelogs: self._wrap_method(
+ self.list_changelogs: gapic_v1.method_async.wrap_method(
self.list_changelogs,
default_timeout=None,
client_info=client_info,
),
- self.get_changelog: self._wrap_method(
+ self.get_changelog: gapic_v1.method_async.wrap_method(
self.get_changelog,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/rest.py
index f30ac5c6a340..ded76c4c3428 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/changelogs/transports/rest.py
@@ -16,30 +16,34 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import changelog
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseChangelogsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import changelog
+
+from .base import ChangelogsTransport
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -249,8 +253,8 @@ class ChangelogsRestStub:
_interceptor: ChangelogsRestInterceptor
-class ChangelogsRestTransport(_BaseChangelogsRestTransport):
- """REST backend synchronous transport for Changelogs.
+class ChangelogsRestTransport(ChangelogsTransport):
+ """REST backend transport for Changelogs.
Service for managing
[Changelogs][google.cloud.dialogflow.cx.v3beta1.Changelog].
@@ -260,6 +264,7 @@ class ChangelogsRestTransport(_BaseChangelogsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -313,12 +318,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -329,33 +343,19 @@ def __init__(
self._interceptor = interceptor or ChangelogsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _GetChangelog(
- _BaseChangelogsRestTransport._BaseGetChangelog, ChangelogsRestStub
- ):
+ class _GetChangelog(ChangelogsRestStub):
def __hash__(self):
- return hash("ChangelogsRestTransport.GetChangelog")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetChangelog")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -384,31 +384,38 @@ def __call__(
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseGetChangelog._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/changelogs/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_changelog(request, metadata)
- transcoded_request = (
- _BaseChangelogsRestTransport._BaseGetChangelog._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = changelog.GetChangelogRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseGetChangelog._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ChangelogsRestTransport._GetChangelog._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -424,33 +431,19 @@ def __call__(
resp = self._interceptor.post_get_changelog(resp)
return resp
- class _ListChangelogs(
- _BaseChangelogsRestTransport._BaseListChangelogs, ChangelogsRestStub
- ):
+ class _ListChangelogs(ChangelogsRestStub):
def __hash__(self):
- return hash("ChangelogsRestTransport.ListChangelogs")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListChangelogs")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -479,29 +472,38 @@ def __call__(
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseListChangelogs._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/changelogs",
+ },
+ ]
request, metadata = self._interceptor.pre_list_changelogs(request, metadata)
- transcoded_request = _BaseChangelogsRestTransport._BaseListChangelogs._get_transcoded_request(
- http_options, request
- )
+ pb_request = changelog.ListChangelogsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseListChangelogs._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ChangelogsRestTransport._ListChangelogs._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -537,34 +539,7 @@ def list_changelogs(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseChangelogsRestTransport._BaseGetLocation, ChangelogsRestStub
- ):
- def __hash__(self):
- return hash("ChangelogsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(ChangelogsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -588,31 +563,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseChangelogsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ChangelogsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -620,9 +596,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -630,34 +605,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseChangelogsRestTransport._BaseListLocations, ChangelogsRestStub
- ):
- def __hash__(self):
- return hash("ChangelogsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(ChangelogsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -681,31 +629,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseChangelogsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ChangelogsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -713,9 +662,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -723,34 +671,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseChangelogsRestTransport._BaseCancelOperation, ChangelogsRestStub
- ):
- def __hash__(self):
- return hash("ChangelogsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(ChangelogsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -771,29 +692,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseChangelogsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseChangelogsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ChangelogsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -807,34 +737,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseChangelogsRestTransport._BaseGetOperation, ChangelogsRestStub
- ):
- def __hash__(self):
- return hash("ChangelogsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(ChangelogsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -858,31 +761,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseChangelogsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ChangelogsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -890,9 +798,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -900,34 +807,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseChangelogsRestTransport._BaseListOperations, ChangelogsRestStub
- ):
- def __hash__(self):
- return hash("ChangelogsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(ChangelogsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -951,29 +831,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseChangelogsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseChangelogsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseChangelogsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ChangelogsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -981,9 +868,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/async_client.py
index e192963f75bc..e2bcd71f622e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -245,7 +246,10 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = ConversationHistoryClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(ConversationHistoryClient).get_transport_class,
+ type(ConversationHistoryClient),
+ )
def __init__(
self,
@@ -433,8 +437,6 @@ async def sample_list_conversations():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -674,7 +676,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -727,7 +733,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -783,7 +793,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -833,7 +847,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -886,7 +904,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/client.py
index 92a4cb32f097..d5e065855d9d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/client.py
@@ -1070,7 +1070,7 @@ def __init__(
Type[ConversationHistoryTransport],
Callable[..., ConversationHistoryTransport],
] = (
- ConversationHistoryClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., ConversationHistoryTransport], transport)
)
@@ -1200,8 +1200,6 @@ def sample_list_conversations():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1448,7 +1446,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1501,7 +1503,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1557,7 +1563,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1607,7 +1617,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1660,7 +1674,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/pagers.py
index db0ab3021bd0..944443832107 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import conversation_history
@@ -65,8 +51,6 @@ def __init__(
request: conversation_history.ListConversationsRequest,
response: conversation_history.ListConversationsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListConversationsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = conversation_history.ListConversationsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[conversation_history.ListConversationsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[conversation_history.Conversation]:
@@ -141,8 +115,6 @@ def __init__(
request: conversation_history.ListConversationsRequest,
response: conversation_history.ListConversationsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -154,17 +126,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListConversationsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = conversation_history.ListConversationsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -177,12 +144,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[conversation_history.Conversation]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/base.py
index 65ef2d55dd80..acd6099057e7 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/base.py
@@ -87,8 +87,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -101,7 +99,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -149,31 +147,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc.py
index ede6c73f2532..cb6e77188cfd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc.py
@@ -124,8 +124,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc_asyncio.py
index 66dba7bb66f4..c4893ddcd058 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -172,8 +171,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -230,9 +228,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -334,60 +329,26 @@ def delete_conversation(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_conversations: self._wrap_method(
+ self.list_conversations: gapic_v1.method_async.wrap_method(
self.list_conversations,
default_timeout=None,
client_info=client_info,
),
- self.get_conversation: self._wrap_method(
+ self.get_conversation: gapic_v1.method_async.wrap_method(
self.get_conversation,
default_timeout=None,
client_info=client_info,
),
- self.delete_conversation: self._wrap_method(
+ self.delete_conversation: gapic_v1.method_async.wrap_method(
self.delete_conversation,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/rest.py
index 09e41ceeccb2..8a58a0fa2c43 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/conversation_history/transports/rest.py
@@ -16,31 +16,35 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import conversation_history
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseConversationHistoryRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import conversation_history
+
+from .base import ConversationHistoryTransport
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -272,8 +276,8 @@ class ConversationHistoryRestStub:
_interceptor: ConversationHistoryRestInterceptor
-class ConversationHistoryRestTransport(_BaseConversationHistoryRestTransport):
- """REST backend synchronous transport for ConversationHistory.
+class ConversationHistoryRestTransport(ConversationHistoryTransport):
+ """REST backend transport for ConversationHistory.
Service for managing conversation history.
@@ -282,6 +286,7 @@ class ConversationHistoryRestTransport(_BaseConversationHistoryRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -335,12 +340,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -351,34 +365,19 @@ def __init__(
self._interceptor = interceptor or ConversationHistoryRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _DeleteConversation(
- _BaseConversationHistoryRestTransport._BaseDeleteConversation,
- ConversationHistoryRestStub,
- ):
+ class _DeleteConversation(ConversationHistoryRestStub):
def __hash__(self):
- return hash("ConversationHistoryRestTransport.DeleteConversation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteConversation")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -401,31 +400,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseDeleteConversation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/conversations/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_conversation(
request, metadata
)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseDeleteConversation._get_transcoded_request(
- http_options, request
- )
+ pb_request = conversation_history.DeleteConversationRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseDeleteConversation._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- ConversationHistoryRestTransport._DeleteConversation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -433,34 +441,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetConversation(
- _BaseConversationHistoryRestTransport._BaseGetConversation,
- ConversationHistoryRestStub,
- ):
+ class _GetConversation(ConversationHistoryRestStub):
def __hash__(self):
- return hash("ConversationHistoryRestTransport.GetConversation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetConversation")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -487,29 +480,40 @@ def __call__(
Represents a conversation.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseGetConversation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/conversations/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_conversation(
request, metadata
)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseGetConversation._get_transcoded_request(
- http_options, request
- )
+ pb_request = conversation_history.GetConversationRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseGetConversation._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ConversationHistoryRestTransport._GetConversation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -525,34 +529,19 @@ def __call__(
resp = self._interceptor.post_get_conversation(resp)
return resp
- class _ListConversations(
- _BaseConversationHistoryRestTransport._BaseListConversations,
- ConversationHistoryRestStub,
- ):
+ class _ListConversations(ConversationHistoryRestStub):
def __hash__(self):
- return hash("ConversationHistoryRestTransport.ListConversations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListConversations")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -581,31 +570,40 @@ def __call__(
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseListConversations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/conversations",
+ },
+ ]
request, metadata = self._interceptor.pre_list_conversations(
request, metadata
)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseListConversations._get_transcoded_request(
- http_options, request
- )
+ pb_request = conversation_history.ListConversationsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseListConversations._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- ConversationHistoryRestTransport._ListConversations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -654,35 +652,7 @@ def list_conversations(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseConversationHistoryRestTransport._BaseGetLocation,
- ConversationHistoryRestStub,
- ):
- def __hash__(self):
- return hash("ConversationHistoryRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(ConversationHistoryRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -706,27 +676,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ConversationHistoryRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -734,9 +709,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -744,35 +718,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseConversationHistoryRestTransport._BaseListLocations,
- ConversationHistoryRestStub,
- ):
- def __hash__(self):
- return hash("ConversationHistoryRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(ConversationHistoryRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -796,27 +742,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ConversationHistoryRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -824,9 +775,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -834,35 +784,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseConversationHistoryRestTransport._BaseCancelOperation,
- ConversationHistoryRestStub,
- ):
- def __hash__(self):
- return hash("ConversationHistoryRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(ConversationHistoryRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -883,29 +805,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ConversationHistoryRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -919,35 +850,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseConversationHistoryRestTransport._BaseGetOperation,
- ConversationHistoryRestStub,
- ):
- def __hash__(self):
- return hash("ConversationHistoryRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(ConversationHistoryRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -971,27 +874,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ConversationHistoryRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -999,9 +911,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1009,35 +920,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseConversationHistoryRestTransport._BaseListOperations,
- ConversationHistoryRestStub,
- ):
- def __hash__(self):
- return hash("ConversationHistoryRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(ConversationHistoryRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1061,27 +944,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseConversationHistoryRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseConversationHistoryRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseConversationHistoryRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ConversationHistoryRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1089,9 +981,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py
index b3e0339c9e4e..bef6c7864ec4 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -196,7 +197,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = DeploymentsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(DeploymentsClient).get_transport_class, type(DeploymentsClient)
+ )
def __init__(
self,
@@ -380,8 +383,6 @@ async def sample_list_deployments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -533,7 +534,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -586,7 +591,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -642,7 +651,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -692,7 +705,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -745,7 +762,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py
index a3c12367ac30..7d53d5744f0d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py
@@ -743,7 +743,7 @@ def __init__(
transport_init: Union[
Type[DeploymentsTransport], Callable[..., DeploymentsTransport]
] = (
- DeploymentsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., DeploymentsTransport], transport)
)
@@ -873,8 +873,6 @@ def sample_list_deployments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1036,7 +1034,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1089,7 +1091,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1145,7 +1151,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1195,7 +1205,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1248,7 +1262,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py
index 4ce8dc064799..79bac5d75dca 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import deployment
@@ -65,8 +51,6 @@ def __init__(
request: deployment.ListDeploymentsRequest,
response: deployment.ListDeploymentsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = deployment.ListDeploymentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[deployment.ListDeploymentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[deployment.Deployment]:
@@ -139,8 +113,6 @@ def __init__(
request: deployment.ListDeploymentsRequest,
response: deployment.ListDeploymentsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListDeploymentsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = deployment.ListDeploymentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[deployment.ListDeploymentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[deployment.Deployment]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py
index 7f1b7ba7158c..4cfbe36bf3db 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py
@@ -86,8 +86,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -100,7 +98,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -143,31 +141,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py
index 14311b47f9e0..94932be363e0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py
@@ -124,8 +124,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py
index 5051f5c0cb40..8c320c6a7e59 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -172,8 +171,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -230,9 +228,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -305,55 +300,21 @@ def get_deployment(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_deployments: self._wrap_method(
+ self.list_deployments: gapic_v1.method_async.wrap_method(
self.list_deployments,
default_timeout=None,
client_info=client_info,
),
- self.get_deployment: self._wrap_method(
+ self.get_deployment: gapic_v1.method_async.wrap_method(
self.get_deployment,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/rest.py
index ff0f51860ece..5bee44236822 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/rest.py
@@ -16,30 +16,34 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import deployment
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseDeploymentsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import deployment
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import DeploymentsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -251,8 +255,8 @@ class DeploymentsRestStub:
_interceptor: DeploymentsRestInterceptor
-class DeploymentsRestTransport(_BaseDeploymentsRestTransport):
- """REST backend synchronous transport for Deployments.
+class DeploymentsRestTransport(DeploymentsTransport):
+ """REST backend transport for Deployments.
Service for managing
[Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment].
@@ -262,6 +266,7 @@ class DeploymentsRestTransport(_BaseDeploymentsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -315,12 +320,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -331,33 +345,19 @@ def __init__(
self._interceptor = interceptor or DeploymentsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _GetDeployment(
- _BaseDeploymentsRestTransport._BaseGetDeployment, DeploymentsRestStub
- ):
+ class _GetDeployment(DeploymentsRestStub):
def __hash__(self):
- return hash("DeploymentsRestTransport.GetDeployment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetDeployment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -391,29 +391,38 @@ def __call__(
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseGetDeployment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/deployments/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_deployment(request, metadata)
- transcoded_request = _BaseDeploymentsRestTransport._BaseGetDeployment._get_transcoded_request(
- http_options, request
- )
+ pb_request = deployment.GetDeploymentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseDeploymentsRestTransport._BaseGetDeployment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = DeploymentsRestTransport._GetDeployment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -429,33 +438,19 @@ def __call__(
resp = self._interceptor.post_get_deployment(resp)
return resp
- class _ListDeployments(
- _BaseDeploymentsRestTransport._BaseListDeployments, DeploymentsRestStub
- ):
+ class _ListDeployments(DeploymentsRestStub):
def __hash__(self):
- return hash("DeploymentsRestTransport.ListDeployments")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListDeployments")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -484,29 +479,40 @@ def __call__(
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseListDeployments._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/deployments",
+ },
+ ]
request, metadata = self._interceptor.pre_list_deployments(
request, metadata
)
- transcoded_request = _BaseDeploymentsRestTransport._BaseListDeployments._get_transcoded_request(
- http_options, request
- )
+ pb_request = deployment.ListDeploymentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseDeploymentsRestTransport._BaseListDeployments._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = DeploymentsRestTransport._ListDeployments._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -544,34 +550,7 @@ def list_deployments(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseDeploymentsRestTransport._BaseGetLocation, DeploymentsRestStub
- ):
- def __hash__(self):
- return hash("DeploymentsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(DeploymentsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -595,31 +574,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseDeploymentsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseDeploymentsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = DeploymentsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -627,9 +607,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -637,34 +616,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseDeploymentsRestTransport._BaseListLocations, DeploymentsRestStub
- ):
- def __hash__(self):
- return hash("DeploymentsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(DeploymentsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -688,29 +640,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseDeploymentsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseDeploymentsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = DeploymentsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -718,9 +673,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -728,34 +682,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseDeploymentsRestTransport._BaseCancelOperation, DeploymentsRestStub
- ):
- def __hash__(self):
- return hash("DeploymentsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(DeploymentsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -776,29 +703,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseDeploymentsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseDeploymentsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = DeploymentsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -812,34 +748,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseDeploymentsRestTransport._BaseGetOperation, DeploymentsRestStub
- ):
- def __hash__(self):
- return hash("DeploymentsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(DeploymentsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -863,31 +772,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseDeploymentsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseDeploymentsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = DeploymentsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -895,9 +809,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -905,34 +818,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseDeploymentsRestTransport._BaseListOperations, DeploymentsRestStub
- ):
- def __hash__(self):
- return hash("DeploymentsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(DeploymentsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -956,27 +842,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseDeploymentsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseDeploymentsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseDeploymentsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = DeploymentsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -984,9 +879,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py
index e6e4f1edc8cd..25c114b9bf58 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -191,7 +192,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = EntityTypesClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(EntityTypesClient).get_transport_class, type(EntityTypesClient)
+ )
def __init__(
self,
@@ -917,8 +920,6 @@ async def sample_list_entity_types():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1156,7 +1157,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1209,7 +1214,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1265,7 +1274,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1315,7 +1328,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1368,7 +1385,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py
index 9477d37f0577..9f38d5c0b905 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py
@@ -666,7 +666,7 @@ def __init__(
transport_init: Union[
Type[EntityTypesTransport], Callable[..., EntityTypesTransport]
] = (
- EntityTypesClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., EntityTypesTransport], transport)
)
@@ -1326,8 +1326,6 @@ def sample_list_entity_types():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1574,7 +1572,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1627,7 +1629,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1683,7 +1689,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1733,7 +1743,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1786,7 +1800,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py
index 8897021a0f24..a2b86a294f4a 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import entity_type
@@ -65,8 +51,6 @@ def __init__(
request: entity_type.ListEntityTypesRequest,
response: entity_type.ListEntityTypesResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListEntityTypesResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = entity_type.ListEntityTypesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[entity_type.EntityType]:
@@ -139,8 +113,6 @@ def __init__(
request: entity_type.ListEntityTypesRequest,
response: entity_type.ListEntityTypesResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListEntityTypesResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = entity_type.ListEntityTypesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[entity_type.EntityType]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py
index ae99cd819a31..6effa17f8cbf 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -170,31 +168,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py
index a069206b7c5c..b89b6afefff2 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py
index 3668dab614d3..44f06cb1febf 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -473,80 +468,46 @@ def import_entity_types(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.get_entity_type: self._wrap_method(
+ self.get_entity_type: gapic_v1.method_async.wrap_method(
self.get_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.create_entity_type: self._wrap_method(
+ self.create_entity_type: gapic_v1.method_async.wrap_method(
self.create_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.update_entity_type: self._wrap_method(
+ self.update_entity_type: gapic_v1.method_async.wrap_method(
self.update_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.delete_entity_type: self._wrap_method(
+ self.delete_entity_type: gapic_v1.method_async.wrap_method(
self.delete_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.list_entity_types: self._wrap_method(
+ self.list_entity_types: gapic_v1.method_async.wrap_method(
self.list_entity_types,
default_timeout=None,
client_info=client_info,
),
- self.export_entity_types: self._wrap_method(
+ self.export_entity_types: gapic_v1.method_async.wrap_method(
self.export_entity_types,
default_timeout=None,
client_info=client_info,
),
- self.import_entity_types: self._wrap_method(
+ self.import_entity_types: gapic_v1.method_async.wrap_method(
self.import_entity_types,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/rest.py
index 69e170ad66c8..07efedfeb52c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type
-from google.cloud.dialogflowcx_v3beta1.types import entity_type
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseEntityTypesRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type
+from google.cloud.dialogflowcx_v3beta1.types import entity_type
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import EntityTypesTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -393,8 +403,8 @@ class EntityTypesRestStub:
_interceptor: EntityTypesRestInterceptor
-class EntityTypesRestTransport(_BaseEntityTypesRestTransport):
- """REST backend synchronous transport for EntityTypes.
+class EntityTypesRestTransport(EntityTypesTransport):
+ """REST backend transport for EntityTypes.
Service for managing
[EntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityType].
@@ -404,6 +414,7 @@ class EntityTypesRestTransport(_BaseEntityTypesRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -457,12 +468,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -532,34 +552,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateEntityType(
- _BaseEntityTypesRestTransport._BaseCreateEntityType, EntityTypesRestStub
- ):
+ class _CreateEntityType(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.CreateEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -621,34 +626,47 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseCreateEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/entityTypes",
+ "body": "entity_type",
+ },
+ ]
request, metadata = self._interceptor.pre_create_entity_type(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseCreateEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_entity_type.CreateEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseEntityTypesRestTransport._BaseCreateEntityType._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseCreateEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._CreateEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -664,33 +682,19 @@ def __call__(
resp = self._interceptor.post_create_entity_type(resp)
return resp
- class _DeleteEntityType(
- _BaseEntityTypesRestTransport._BaseDeleteEntityType, EntityTypesRestStub
- ):
+ class _DeleteEntityType(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.DeleteEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -713,29 +717,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseDeleteEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/entityTypes/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_entity_type(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseDeleteEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = entity_type.DeleteEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseDeleteEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._DeleteEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -743,34 +758,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _ExportEntityTypes(
- _BaseEntityTypesRestTransport._BaseExportEntityTypes, EntityTypesRestStub
- ):
+ class _ExportEntityTypes(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.ExportEntityTypes")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportEntityTypes")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -800,34 +800,47 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseExportEntityTypes._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/entityTypes:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_entity_types(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseExportEntityTypes._get_transcoded_request(
- http_options, request
- )
+ pb_request = entity_type.ExportEntityTypesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseEntityTypesRestTransport._BaseExportEntityTypes._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseExportEntityTypes._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._ExportEntityTypes._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -841,33 +854,19 @@ def __call__(
resp = self._interceptor.post_export_entity_types(resp)
return resp
- class _GetEntityType(
- _BaseEntityTypesRestTransport._BaseGetEntityType, EntityTypesRestStub
- ):
+ class _GetEntityType(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.GetEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -929,29 +928,38 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseGetEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/entityTypes/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_entity_type(request, metadata)
- transcoded_request = _BaseEntityTypesRestTransport._BaseGetEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = entity_type.GetEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEntityTypesRestTransport._BaseGetEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._GetEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -967,34 +975,19 @@ def __call__(
resp = self._interceptor.post_get_entity_type(resp)
return resp
- class _ImportEntityTypes(
- _BaseEntityTypesRestTransport._BaseImportEntityTypes, EntityTypesRestStub
- ):
+ class _ImportEntityTypes(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.ImportEntityTypes")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ImportEntityTypes")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1024,34 +1017,47 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseImportEntityTypes._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/entityTypes:import",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_import_entity_types(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseImportEntityTypes._get_transcoded_request(
- http_options, request
- )
+ pb_request = entity_type.ImportEntityTypesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseEntityTypesRestTransport._BaseImportEntityTypes._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseImportEntityTypes._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._ImportEntityTypes._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1065,33 +1071,19 @@ def __call__(
resp = self._interceptor.post_import_entity_types(resp)
return resp
- class _ListEntityTypes(
- _BaseEntityTypesRestTransport._BaseListEntityTypes, EntityTypesRestStub
- ):
+ class _ListEntityTypes(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.ListEntityTypes")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListEntityTypes")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1120,29 +1112,40 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseListEntityTypes._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/entityTypes",
+ },
+ ]
request, metadata = self._interceptor.pre_list_entity_types(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseListEntityTypes._get_transcoded_request(
- http_options, request
- )
+ pb_request = entity_type.ListEntityTypesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseListEntityTypes._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._ListEntityTypes._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1158,34 +1161,19 @@ def __call__(
resp = self._interceptor.post_list_entity_types(resp)
return resp
- class _UpdateEntityType(
- _BaseEntityTypesRestTransport._BaseUpdateEntityType, EntityTypesRestStub
- ):
+ class _UpdateEntityType(EntityTypesRestStub):
def __hash__(self):
- return hash("EntityTypesRestTransport.UpdateEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1247,34 +1235,47 @@ def __call__(
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseUpdateEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{entity_type.name=projects/*/locations/*/agents/*/entityTypes/*}",
+ "body": "entity_type",
+ },
+ ]
request, metadata = self._interceptor.pre_update_entity_type(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseUpdateEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_entity_type.UpdateEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseEntityTypesRestTransport._BaseUpdateEntityType._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseUpdateEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EntityTypesRestTransport._UpdateEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1356,34 +1357,7 @@ def update_entity_type(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseEntityTypesRestTransport._BaseGetLocation, EntityTypesRestStub
- ):
- def __hash__(self):
- return hash("EntityTypesRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(EntityTypesRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1407,31 +1381,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseEntityTypesRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEntityTypesRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EntityTypesRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1439,9 +1414,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1449,34 +1423,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseEntityTypesRestTransport._BaseListLocations, EntityTypesRestStub
- ):
- def __hash__(self):
- return hash("EntityTypesRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(EntityTypesRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1500,29 +1447,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseEntityTypesRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEntityTypesRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EntityTypesRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1530,9 +1480,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1540,34 +1489,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseEntityTypesRestTransport._BaseCancelOperation, EntityTypesRestStub
- ):
- def __hash__(self):
- return hash("EntityTypesRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(EntityTypesRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1588,29 +1510,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseEntityTypesRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EntityTypesRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1624,34 +1555,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseEntityTypesRestTransport._BaseGetOperation, EntityTypesRestStub
- ):
- def __hash__(self):
- return hash("EntityTypesRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(EntityTypesRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1675,31 +1579,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseEntityTypesRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEntityTypesRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EntityTypesRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1707,9 +1616,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1717,34 +1625,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseEntityTypesRestTransport._BaseListOperations, EntityTypesRestStub
- ):
- def __hash__(self):
- return hash("EntityTypesRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(EntityTypesRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1768,27 +1649,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseEntityTypesRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseEntityTypesRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEntityTypesRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EntityTypesRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1796,9 +1686,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py
index 7fd8e34fa75e..4a267bd75a08 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -211,7 +212,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = EnvironmentsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)
+ )
def __init__(
self,
@@ -395,8 +398,6 @@ async def sample_list_environments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1053,8 +1054,6 @@ async def sample_lookup_environment_history():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1288,8 +1287,6 @@ async def sample_list_continuous_test_results():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1439,7 +1436,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1492,7 +1493,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1548,7 +1553,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1598,7 +1607,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1651,7 +1664,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/client.py
index c423e2e996e6..0d55415d3157 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/client.py
@@ -818,7 +818,7 @@ def __init__(
transport_init: Union[
Type[EnvironmentsTransport], Callable[..., EnvironmentsTransport]
] = (
- EnvironmentsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., EnvironmentsTransport], transport)
)
@@ -948,8 +948,6 @@ def sample_list_environments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1593,8 +1591,6 @@ def sample_lookup_environment_history():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1825,8 +1821,6 @@ def sample_list_continuous_test_results():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1987,7 +1981,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2040,7 +2038,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2096,7 +2098,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2146,7 +2152,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2199,7 +2209,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py
index 6548a80c3cac..c7ec766d5905 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import environment
@@ -65,8 +51,6 @@ def __init__(
request: environment.ListEnvironmentsRequest,
response: environment.ListEnvironmentsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.ListEnvironmentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[environment.ListEnvironmentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[environment.Environment]:
@@ -139,8 +113,6 @@ def __init__(
request: environment.ListEnvironmentsRequest,
response: environment.ListEnvironmentsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.ListEnvironmentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[environment.Environment]:
@@ -217,8 +179,6 @@ def __init__(
request: environment.LookupEnvironmentHistoryRequest,
response: environment.LookupEnvironmentHistoryResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -230,17 +190,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.LookupEnvironmentHistoryRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -251,12 +206,7 @@ def pages(self) -> Iterator[environment.LookupEnvironmentHistoryResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[environment.Environment]:
@@ -291,8 +241,6 @@ def __init__(
request: environment.LookupEnvironmentHistoryRequest,
response: environment.LookupEnvironmentHistoryResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -304,17 +252,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.LookupEnvironmentHistoryRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -327,12 +270,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[environment.Environment]:
@@ -371,8 +309,6 @@ def __init__(
request: environment.ListContinuousTestResultsRequest,
response: environment.ListContinuousTestResultsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -384,17 +320,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.ListContinuousTestResultsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -405,12 +336,7 @@ def pages(self) -> Iterator[environment.ListContinuousTestResultsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[environment.ContinuousTestResult]:
@@ -445,8 +371,6 @@ def __init__(
request: environment.ListContinuousTestResultsRequest,
response: environment.ListContinuousTestResultsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -458,17 +382,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = environment.ListContinuousTestResultsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -481,12 +400,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[environment.ContinuousTestResult]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py
index bed8805bf24b..e588793c7cfc 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -180,31 +178,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py
index 18b3cfbd1b79..dc1b890aacdc 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py
index 4414d41d6d5e..a0ad1130f2d8 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -568,90 +563,56 @@ def deploy_flow(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_environments: self._wrap_method(
+ self.list_environments: gapic_v1.method_async.wrap_method(
self.list_environments,
default_timeout=None,
client_info=client_info,
),
- self.get_environment: self._wrap_method(
+ self.get_environment: gapic_v1.method_async.wrap_method(
self.get_environment,
default_timeout=None,
client_info=client_info,
),
- self.create_environment: self._wrap_method(
+ self.create_environment: gapic_v1.method_async.wrap_method(
self.create_environment,
default_timeout=None,
client_info=client_info,
),
- self.update_environment: self._wrap_method(
+ self.update_environment: gapic_v1.method_async.wrap_method(
self.update_environment,
default_timeout=None,
client_info=client_info,
),
- self.delete_environment: self._wrap_method(
+ self.delete_environment: gapic_v1.method_async.wrap_method(
self.delete_environment,
default_timeout=None,
client_info=client_info,
),
- self.lookup_environment_history: self._wrap_method(
+ self.lookup_environment_history: gapic_v1.method_async.wrap_method(
self.lookup_environment_history,
default_timeout=None,
client_info=client_info,
),
- self.run_continuous_test: self._wrap_method(
+ self.run_continuous_test: gapic_v1.method_async.wrap_method(
self.run_continuous_test,
default_timeout=None,
client_info=client_info,
),
- self.list_continuous_test_results: self._wrap_method(
+ self.list_continuous_test_results: gapic_v1.method_async.wrap_method(
self.list_continuous_test_results,
default_timeout=None,
client_info=client_info,
),
- self.deploy_flow: self._wrap_method(
+ self.deploy_flow: gapic_v1.method_async.wrap_method(
self.deploy_flow,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/rest.py
index c924577a3a08..81f222940056 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/environments/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment
-from google.cloud.dialogflowcx_v3beta1.types import environment
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseEnvironmentsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment
+from google.cloud.dialogflowcx_v3beta1.types import environment
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import EnvironmentsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -455,8 +465,8 @@ class EnvironmentsRestStub:
_interceptor: EnvironmentsRestInterceptor
-class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport):
- """REST backend synchronous transport for Environments.
+class EnvironmentsRestTransport(EnvironmentsTransport):
+ """REST backend transport for Environments.
Service for managing
[Environments][google.cloud.dialogflow.cx.v3beta1.Environment].
@@ -466,6 +476,7 @@ class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -519,12 +530,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -594,34 +614,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateEnvironment(
- _BaseEnvironmentsRestTransport._BaseCreateEnvironment, EnvironmentsRestStub
- ):
+ class _CreateEnvironment(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.CreateEnvironment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateEnvironment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -651,34 +656,47 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/environments",
+ "body": "environment",
+ },
+ ]
request, metadata = self._interceptor.pre_create_environment(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_environment.CreateEnvironmentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._CreateEnvironment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -692,33 +710,19 @@ def __call__(
resp = self._interceptor.post_create_environment(resp)
return resp
- class _DeleteEnvironment(
- _BaseEnvironmentsRestTransport._BaseDeleteEnvironment, EnvironmentsRestStub
- ):
+ class _DeleteEnvironment(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.DeleteEnvironment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteEnvironment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -741,29 +745,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_environment(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.DeleteEnvironmentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._DeleteEnvironment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -771,34 +786,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _DeployFlow(
- _BaseEnvironmentsRestTransport._BaseDeployFlow, EnvironmentsRestStub
- ):
+ class _DeployFlow(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.DeployFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("DeployFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -828,38 +828,45 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseDeployFlow._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{environment=projects/*/locations/*/agents/*/environments/*}:deployFlow",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_deploy_flow(request, metadata)
- transcoded_request = (
- _BaseEnvironmentsRestTransport._BaseDeployFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = environment.DeployFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseEnvironmentsRestTransport._BaseDeployFlow._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEnvironmentsRestTransport._BaseDeployFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._DeployFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -873,33 +880,19 @@ def __call__(
resp = self._interceptor.post_deploy_flow(resp)
return resp
- class _GetEnvironment(
- _BaseEnvironmentsRestTransport._BaseGetEnvironment, EnvironmentsRestStub
- ):
+ class _GetEnvironment(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.GetEnvironment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetEnvironment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -941,27 +934,38 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_environment(request, metadata)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.GetEnvironmentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._GetEnvironment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -977,34 +981,19 @@ def __call__(
resp = self._interceptor.post_get_environment(resp)
return resp
- class _ListContinuousTestResults(
- _BaseEnvironmentsRestTransport._BaseListContinuousTestResults,
- EnvironmentsRestStub,
- ):
+ class _ListContinuousTestResults(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.ListContinuousTestResults")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListContinuousTestResults")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1034,31 +1023,40 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseListContinuousTestResults._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/continuousTestResults",
+ },
+ ]
request, metadata = self._interceptor.pre_list_continuous_test_results(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseListContinuousTestResults._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.ListContinuousTestResultsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseListContinuousTestResults._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- EnvironmentsRestTransport._ListContinuousTestResults._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1074,33 +1072,19 @@ def __call__(
resp = self._interceptor.post_list_continuous_test_results(resp)
return resp
- class _ListEnvironments(
- _BaseEnvironmentsRestTransport._BaseListEnvironments, EnvironmentsRestStub
- ):
+ class _ListEnvironments(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.ListEnvironments")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListEnvironments")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1129,29 +1113,40 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseListEnvironments._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/environments",
+ },
+ ]
request, metadata = self._interceptor.pre_list_environments(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.ListEnvironmentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._ListEnvironments._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1167,34 +1162,19 @@ def __call__(
resp = self._interceptor.post_list_environments(resp)
return resp
- class _LookupEnvironmentHistory(
- _BaseEnvironmentsRestTransport._BaseLookupEnvironmentHistory,
- EnvironmentsRestStub,
- ):
+ class _LookupEnvironmentHistory(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.LookupEnvironmentHistory")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("LookupEnvironmentHistory")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1224,31 +1204,40 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseLookupEnvironmentHistory._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}:lookupEnvironmentHistory",
+ },
+ ]
request, metadata = self._interceptor.pre_lookup_environment_history(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseLookupEnvironmentHistory._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.LookupEnvironmentHistoryRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseLookupEnvironmentHistory._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- EnvironmentsRestTransport._LookupEnvironmentHistory._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1264,34 +1253,19 @@ def __call__(
resp = self._interceptor.post_lookup_environment_history(resp)
return resp
- class _RunContinuousTest(
- _BaseEnvironmentsRestTransport._BaseRunContinuousTest, EnvironmentsRestStub
- ):
+ class _RunContinuousTest(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.RunContinuousTest")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("RunContinuousTest")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1321,34 +1295,47 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseRunContinuousTest._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{environment=projects/*/locations/*/agents/*/environments/*}:runContinuousTest",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_run_continuous_test(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseRunContinuousTest._get_transcoded_request(
- http_options, request
- )
+ pb_request = environment.RunContinuousTestRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseEnvironmentsRestTransport._BaseRunContinuousTest._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseRunContinuousTest._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._RunContinuousTest._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1362,34 +1349,21 @@ def __call__(
resp = self._interceptor.post_run_continuous_test(resp)
return resp
- class _UpdateEnvironment(
- _BaseEnvironmentsRestTransport._BaseUpdateEnvironment, EnvironmentsRestStub
- ):
+ class _UpdateEnvironment(EnvironmentsRestStub):
def __hash__(self):
- return hash("EnvironmentsRestTransport.UpdateEnvironment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateEnvironment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "updateMask": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1419,34 +1393,47 @@ def __call__(
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{environment.name=projects/*/locations/*/agents/*/environments/*}",
+ "body": "environment",
+ },
+ ]
request, metadata = self._interceptor.pre_update_environment(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_environment.UpdateEnvironmentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = EnvironmentsRestTransport._UpdateEnvironment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1548,34 +1535,7 @@ def update_environment(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseEnvironmentsRestTransport._BaseGetLocation, EnvironmentsRestStub
- ):
- def __hash__(self):
- return hash("EnvironmentsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(EnvironmentsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1599,31 +1559,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseEnvironmentsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEnvironmentsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EnvironmentsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1631,9 +1592,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1641,34 +1601,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseEnvironmentsRestTransport._BaseListLocations, EnvironmentsRestStub
- ):
- def __hash__(self):
- return hash("EnvironmentsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(EnvironmentsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1692,27 +1625,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EnvironmentsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1720,9 +1658,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1730,34 +1667,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseEnvironmentsRestTransport._BaseCancelOperation, EnvironmentsRestStub
- ):
- def __hash__(self):
- return hash("EnvironmentsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(EnvironmentsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1778,29 +1688,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EnvironmentsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1814,34 +1733,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseEnvironmentsRestTransport._BaseGetOperation, EnvironmentsRestStub
- ):
- def __hash__(self):
- return hash("EnvironmentsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(EnvironmentsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1865,29 +1757,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseEnvironmentsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EnvironmentsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1895,9 +1794,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1905,34 +1803,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseEnvironmentsRestTransport._BaseListOperations, EnvironmentsRestStub
- ):
- def __hash__(self):
- return hash("EnvironmentsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(EnvironmentsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1956,27 +1827,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseEnvironmentsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseEnvironmentsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseEnvironmentsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = EnvironmentsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1984,9 +1864,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/async_client.py
index c174dd7908e9..2edc8911444b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -192,7 +193,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = ExamplesClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(ExamplesClient).get_transport_class, type(ExamplesClient)
+ )
def __init__(
self,
@@ -592,8 +595,6 @@ async def sample_list_examples():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -867,7 +868,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -920,7 +925,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -976,7 +985,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1026,7 +1039,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1079,7 +1096,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/client.py
index 9de2bf37efce..9d2d6f241003 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/client.py
@@ -739,7 +739,7 @@ def __init__(
transport_init: Union[
Type[ExamplesTransport], Callable[..., ExamplesTransport]
] = (
- ExamplesClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., ExamplesTransport], transport)
)
@@ -1079,8 +1079,6 @@ def sample_list_examples():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1361,7 +1359,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1414,7 +1416,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1470,7 +1476,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1520,7 +1530,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1573,7 +1587,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/pagers.py
index 8942f018383b..be81360b09cd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import example
@@ -65,8 +51,6 @@ def __init__(
request: example.ListExamplesRequest,
response: example.ListExamplesResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListExamplesResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = example.ListExamplesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[example.ListExamplesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[example.Example]:
@@ -139,8 +113,6 @@ def __init__(
request: example.ListExamplesRequest,
response: example.ListExamplesResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListExamplesResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = example.ListExamplesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[example.ListExamplesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[example.Example]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/base.py
index 10326bdd4871..b9df55079025 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -160,31 +158,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc.py
index e4b0480e5ed0..bd20c289c4cd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc_asyncio.py
index 8067ddefaf30..2a9b13393ff1 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -382,70 +377,36 @@ def update_example(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.create_example: self._wrap_method(
+ self.create_example: gapic_v1.method_async.wrap_method(
self.create_example,
default_timeout=None,
client_info=client_info,
),
- self.delete_example: self._wrap_method(
+ self.delete_example: gapic_v1.method_async.wrap_method(
self.delete_example,
default_timeout=None,
client_info=client_info,
),
- self.list_examples: self._wrap_method(
+ self.list_examples: gapic_v1.method_async.wrap_method(
self.list_examples,
default_timeout=None,
client_info=client_info,
),
- self.get_example: self._wrap_method(
+ self.get_example: gapic_v1.method_async.wrap_method(
self.get_example,
default_timeout=None,
client_info=client_info,
),
- self.update_example: self._wrap_method(
+ self.update_example: gapic_v1.method_async.wrap_method(
self.update_example,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/rest.py
index 697f8c72d27a..0f4425fcbcdf 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/examples/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import example
-from google.cloud.dialogflowcx_v3beta1.types import example as gcdc_example
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseExamplesRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import example
+from google.cloud.dialogflowcx_v3beta1.types import example as gcdc_example
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import ExamplesTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -323,8 +327,8 @@ class ExamplesRestStub:
_interceptor: ExamplesRestInterceptor
-class ExamplesRestTransport(_BaseExamplesRestTransport):
- """REST backend synchronous transport for Examples.
+class ExamplesRestTransport(ExamplesTransport):
+ """REST backend transport for Examples.
Service for managing
[Examples][google.cloud.dialogflow.cx.v3beta1.Example].
@@ -334,6 +338,7 @@ class ExamplesRestTransport(_BaseExamplesRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -387,12 +392,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -403,34 +417,19 @@ def __init__(
self._interceptor = interceptor or ExamplesRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateExample(
- _BaseExamplesRestTransport._BaseCreateExample, ExamplesRestStub
- ):
+ class _CreateExample(ExamplesRestStub):
def __hash__(self):
- return hash("ExamplesRestTransport.CreateExample")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateExample")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -463,36 +462,45 @@ def __call__(
"""
- http_options = (
- _BaseExamplesRestTransport._BaseCreateExample._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples",
+ "body": "example",
+ },
+ ]
request, metadata = self._interceptor.pre_create_example(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseCreateExample._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_example.CreateExampleRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseExamplesRestTransport._BaseCreateExample._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseCreateExample._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExamplesRestTransport._CreateExample._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -508,33 +516,19 @@ def __call__(
resp = self._interceptor.post_create_example(resp)
return resp
- class _DeleteExample(
- _BaseExamplesRestTransport._BaseDeleteExample, ExamplesRestStub
- ):
+ class _DeleteExample(ExamplesRestStub):
def __hash__(self):
- return hash("ExamplesRestTransport.DeleteExample")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteExample")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -557,31 +551,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseDeleteExample._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_example(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseDeleteExample._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = example.DeleteExampleRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseDeleteExample._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExamplesRestTransport._DeleteExample._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -589,31 +590,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetExample(_BaseExamplesRestTransport._BaseGetExample, ExamplesRestStub):
+ class _GetExample(ExamplesRestStub):
def __hash__(self):
- return hash("ExamplesRestTransport.GetExample")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetExample")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -646,31 +635,38 @@ def __call__(
"""
- http_options = (
- _BaseExamplesRestTransport._BaseGetExample._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_example(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseGetExample._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = example.GetExampleRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseGetExample._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExamplesRestTransport._GetExample._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -686,31 +682,19 @@ def __call__(
resp = self._interceptor.post_get_example(resp)
return resp
- class _ListExamples(_BaseExamplesRestTransport._BaseListExamples, ExamplesRestStub):
+ class _ListExamples(ExamplesRestStub):
def __hash__(self):
- return hash("ExamplesRestTransport.ListExamples")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListExamples")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -739,31 +723,38 @@ def __call__(
"""
- http_options = (
- _BaseExamplesRestTransport._BaseListExamples._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples",
+ },
+ ]
request, metadata = self._interceptor.pre_list_examples(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseListExamples._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = example.ListExamplesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseListExamples._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExamplesRestTransport._ListExamples._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -779,34 +770,19 @@ def __call__(
resp = self._interceptor.post_list_examples(resp)
return resp
- class _UpdateExample(
- _BaseExamplesRestTransport._BaseUpdateExample, ExamplesRestStub
- ):
+ class _UpdateExample(ExamplesRestStub):
def __hash__(self):
- return hash("ExamplesRestTransport.UpdateExample")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateExample")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -839,36 +815,45 @@ def __call__(
"""
- http_options = (
- _BaseExamplesRestTransport._BaseUpdateExample._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{example.name=projects/*/locations/*/agents/*/playbooks/*/examples/*}",
+ "body": "example",
+ },
+ ]
request, metadata = self._interceptor.pre_update_example(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseUpdateExample._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_example.UpdateExampleRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseExamplesRestTransport._BaseUpdateExample._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseUpdateExample._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExamplesRestTransport._UpdateExample._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -926,32 +911,7 @@ def update_example(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseExamplesRestTransport._BaseGetLocation, ExamplesRestStub):
- def __hash__(self):
- return hash("ExamplesRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(ExamplesRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -975,31 +935,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExamplesRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1007,9 +968,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1017,34 +977,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseExamplesRestTransport._BaseListLocations, ExamplesRestStub
- ):
- def __hash__(self):
- return hash("ExamplesRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(ExamplesRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1068,31 +1001,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExamplesRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1100,9 +1034,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1110,34 +1043,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseExamplesRestTransport._BaseCancelOperation, ExamplesRestStub
- ):
- def __hash__(self):
- return hash("ExamplesRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(ExamplesRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1158,33 +1064,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExamplesRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1198,32 +1109,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseExamplesRestTransport._BaseGetOperation, ExamplesRestStub):
- def __hash__(self):
- return hash("ExamplesRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(ExamplesRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1247,31 +1133,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExamplesRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1279,9 +1170,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1289,34 +1179,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseExamplesRestTransport._BaseListOperations, ExamplesRestStub
- ):
- def __hash__(self):
- return hash("ExamplesRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(ExamplesRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1340,31 +1203,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseExamplesRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseExamplesRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExamplesRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExamplesRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1372,9 +1240,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py
index 9be28c286ab8..c6c44a7fe186 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -193,7 +194,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = ExperimentsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(ExperimentsClient).get_transport_class, type(ExperimentsClient)
+ )
def __init__(
self,
@@ -377,8 +380,6 @@ async def sample_list_experiments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1087,7 +1088,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1140,7 +1145,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1196,7 +1205,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1246,7 +1259,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1299,7 +1316,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py
index d74f70538ba8..4597cb54298b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py
@@ -694,7 +694,7 @@ def __init__(
transport_init: Union[
Type[ExperimentsTransport], Callable[..., ExperimentsTransport]
] = (
- ExperimentsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., ExperimentsTransport], transport)
)
@@ -824,8 +824,6 @@ def sample_list_experiments():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1529,7 +1527,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1582,7 +1584,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1638,7 +1644,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1688,7 +1698,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1741,7 +1755,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py
index c41558359ca8..303905541320 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import experiment
@@ -65,8 +51,6 @@ def __init__(
request: experiment.ListExperimentsRequest,
response: experiment.ListExperimentsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = experiment.ListExperimentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[experiment.ListExperimentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[experiment.Experiment]:
@@ -139,8 +113,6 @@ def __init__(
request: experiment.ListExperimentsRequest,
response: experiment.ListExperimentsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = experiment.ListExperimentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[experiment.ListExperimentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[experiment.Experiment]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py
index e2ba0c6c4d6c..7bfa740e5894 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -170,31 +168,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py
index 65c4ff8e731b..d9d65c11e39b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py
index 61d3843c9b71..5335cca779cd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -454,80 +449,46 @@ def stop_experiment(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_experiments: self._wrap_method(
+ self.list_experiments: gapic_v1.method_async.wrap_method(
self.list_experiments,
default_timeout=None,
client_info=client_info,
),
- self.get_experiment: self._wrap_method(
+ self.get_experiment: gapic_v1.method_async.wrap_method(
self.get_experiment,
default_timeout=None,
client_info=client_info,
),
- self.create_experiment: self._wrap_method(
+ self.create_experiment: gapic_v1.method_async.wrap_method(
self.create_experiment,
default_timeout=None,
client_info=client_info,
),
- self.update_experiment: self._wrap_method(
+ self.update_experiment: gapic_v1.method_async.wrap_method(
self.update_experiment,
default_timeout=None,
client_info=client_info,
),
- self.delete_experiment: self._wrap_method(
+ self.delete_experiment: gapic_v1.method_async.wrap_method(
self.delete_experiment,
default_timeout=None,
client_info=client_info,
),
- self.start_experiment: self._wrap_method(
+ self.start_experiment: gapic_v1.method_async.wrap_method(
self.start_experiment,
default_timeout=None,
client_info=client_info,
),
- self.stop_experiment: self._wrap_method(
+ self.stop_experiment: gapic_v1.method_async.wrap_method(
self.stop_experiment,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/rest.py
index d7343982b549..66478281b563 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment
-from google.cloud.dialogflowcx_v3beta1.types import experiment
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseExperimentsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment
+from google.cloud.dialogflowcx_v3beta1.types import experiment
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import ExperimentsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -393,8 +397,8 @@ class ExperimentsRestStub:
_interceptor: ExperimentsRestInterceptor
-class ExperimentsRestTransport(_BaseExperimentsRestTransport):
- """REST backend synchronous transport for Experiments.
+class ExperimentsRestTransport(ExperimentsTransport):
+ """REST backend transport for Experiments.
Service for managing
[Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment].
@@ -404,6 +408,7 @@ class ExperimentsRestTransport(_BaseExperimentsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -457,12 +462,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -473,34 +487,19 @@ def __init__(
self._interceptor = interceptor or ExperimentsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateExperiment(
- _BaseExperimentsRestTransport._BaseCreateExperiment, ExperimentsRestStub
- ):
+ class _CreateExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.CreateExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -529,34 +528,47 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseCreateExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/experiments",
+ "body": "experiment",
+ },
+ ]
request, metadata = self._interceptor.pre_create_experiment(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseCreateExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_experiment.CreateExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseExperimentsRestTransport._BaseCreateExperiment._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseCreateExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._CreateExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -572,33 +584,19 @@ def __call__(
resp = self._interceptor.post_create_experiment(resp)
return resp
- class _DeleteExperiment(
- _BaseExperimentsRestTransport._BaseDeleteExperiment, ExperimentsRestStub
- ):
+ class _DeleteExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.DeleteExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -621,29 +619,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseDeleteExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_experiment(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseDeleteExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = experiment.DeleteExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseDeleteExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._DeleteExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -651,33 +660,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetExperiment(
- _BaseExperimentsRestTransport._BaseGetExperiment, ExperimentsRestStub
- ):
+ class _GetExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.GetExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -706,29 +701,38 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseGetExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_experiment(request, metadata)
- transcoded_request = _BaseExperimentsRestTransport._BaseGetExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = experiment.GetExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExperimentsRestTransport._BaseGetExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._GetExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -744,33 +748,19 @@ def __call__(
resp = self._interceptor.post_get_experiment(resp)
return resp
- class _ListExperiments(
- _BaseExperimentsRestTransport._BaseListExperiments, ExperimentsRestStub
- ):
+ class _ListExperiments(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.ListExperiments")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListExperiments")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -799,29 +789,40 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseListExperiments._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/experiments",
+ },
+ ]
request, metadata = self._interceptor.pre_list_experiments(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseListExperiments._get_transcoded_request(
- http_options, request
- )
+ pb_request = experiment.ListExperimentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseListExperiments._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._ListExperiments._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -837,34 +838,19 @@ def __call__(
resp = self._interceptor.post_list_experiments(resp)
return resp
- class _StartExperiment(
- _BaseExperimentsRestTransport._BaseStartExperiment, ExperimentsRestStub
- ):
+ class _StartExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.StartExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("StartExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -893,34 +879,47 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseStartExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:start",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_start_experiment(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseStartExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = experiment.StartExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseExperimentsRestTransport._BaseStartExperiment._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseStartExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._StartExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -936,34 +935,19 @@ def __call__(
resp = self._interceptor.post_start_experiment(resp)
return resp
- class _StopExperiment(
- _BaseExperimentsRestTransport._BaseStopExperiment, ExperimentsRestStub
- ):
+ class _StopExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.StopExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("StopExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -992,32 +976,45 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseStopExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:stop",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_stop_experiment(request, metadata)
- transcoded_request = _BaseExperimentsRestTransport._BaseStopExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = experiment.StopExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseExperimentsRestTransport._BaseStopExperiment._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseStopExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._StopExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1033,34 +1030,21 @@ def __call__(
resp = self._interceptor.post_stop_experiment(resp)
return resp
- class _UpdateExperiment(
- _BaseExperimentsRestTransport._BaseUpdateExperiment, ExperimentsRestStub
- ):
+ class _UpdateExperiment(ExperimentsRestStub):
def __hash__(self):
- return hash("ExperimentsRestTransport.UpdateExperiment")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateExperiment")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "updateMask": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1089,34 +1073,47 @@ def __call__(
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseUpdateExperiment._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{experiment.name=projects/*/locations/*/agents/*/environments/*/experiments/*}",
+ "body": "experiment",
+ },
+ ]
request, metadata = self._interceptor.pre_update_experiment(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseUpdateExperiment._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_experiment.UpdateExperimentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseExperimentsRestTransport._BaseUpdateExperiment._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseUpdateExperiment._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ExperimentsRestTransport._UpdateExperiment._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1198,34 +1195,7 @@ def update_experiment(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseExperimentsRestTransport._BaseGetLocation, ExperimentsRestStub
- ):
- def __hash__(self):
- return hash("ExperimentsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(ExperimentsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1249,31 +1219,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseExperimentsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExperimentsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExperimentsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1281,9 +1252,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1291,34 +1261,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseExperimentsRestTransport._BaseListLocations, ExperimentsRestStub
- ):
- def __hash__(self):
- return hash("ExperimentsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(ExperimentsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1342,29 +1285,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseExperimentsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExperimentsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExperimentsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1372,9 +1318,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1382,34 +1327,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseExperimentsRestTransport._BaseCancelOperation, ExperimentsRestStub
- ):
- def __hash__(self):
- return hash("ExperimentsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(ExperimentsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1430,29 +1348,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseExperimentsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExperimentsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1466,34 +1393,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseExperimentsRestTransport._BaseGetOperation, ExperimentsRestStub
- ):
- def __hash__(self):
- return hash("ExperimentsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(ExperimentsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1517,31 +1417,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseExperimentsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseExperimentsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExperimentsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1549,9 +1454,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1559,34 +1463,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseExperimentsRestTransport._BaseListOperations, ExperimentsRestStub
- ):
- def __hash__(self):
- return hash("ExperimentsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(ExperimentsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1610,27 +1487,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseExperimentsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseExperimentsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseExperimentsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ExperimentsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1638,9 +1524,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py
index 5e04908cba04..653b93229767 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -86,8 +87,6 @@ class FlowsAsyncClient:
parse_intent_path = staticmethod(FlowsClient.parse_intent_path)
page_path = staticmethod(FlowsClient.page_path)
parse_page_path = staticmethod(FlowsClient.parse_page_path)
- playbook_path = staticmethod(FlowsClient.playbook_path)
- parse_playbook_path = staticmethod(FlowsClient.parse_playbook_path)
tool_path = staticmethod(FlowsClient.tool_path)
parse_tool_path = staticmethod(FlowsClient.parse_tool_path)
transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path)
@@ -208,7 +207,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = FlowsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(FlowsClient).get_transport_class, type(FlowsClient)
+ )
def __init__(
self,
@@ -626,8 +627,6 @@ async def sample_list_flows():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1497,7 +1496,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1550,7 +1553,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1606,7 +1613,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1656,7 +1667,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1709,7 +1724,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/client.py
index 60ff2e6da0eb..61298efb4c04 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/client.py
@@ -293,30 +293,6 @@ def parse_page_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
- @staticmethod
- def playbook_path(
- project: str,
- location: str,
- agent: str,
- playbook: str,
- ) -> str:
- """Returns a fully-qualified playbook string."""
- return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
- project=project,
- location=location,
- agent=agent,
- playbook=playbook,
- )
-
- @staticmethod
- def parse_playbook_path(path: str) -> Dict[str, str]:
- """Parses a playbook path into its component segments."""
- m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$",
- path,
- )
- return m.groupdict() if m else {}
-
@staticmethod
def tool_path(
project: str,
@@ -843,7 +819,7 @@ def __init__(
transport_init: Union[
Type[FlowsTransport], Callable[..., FlowsTransport]
] = (
- FlowsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., FlowsTransport], transport)
)
@@ -1201,8 +1177,6 @@ def sample_list_flows():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -2071,7 +2045,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2124,7 +2102,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2180,7 +2162,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2230,7 +2216,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2283,7 +2273,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py
index f846299a4692..e681ff89f28e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import flow
@@ -65,8 +51,6 @@ def __init__(
request: flow.ListFlowsRequest,
response: flow.ListFlowsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = flow.ListFlowsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[flow.ListFlowsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[flow.Flow]:
@@ -139,8 +113,6 @@ def __init__(
request: flow.ListFlowsRequest,
response: flow.ListFlowsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = flow.ListFlowsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[flow.ListFlowsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[flow.Flow]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py
index 9f907e1092e9..3bb9f36be675 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -185,31 +183,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py
index 9f416a47e40f..5afdc254a46c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py
index e2262afb0414..a12c39d973f3 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -582,95 +577,61 @@ def export_flow(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.create_flow: self._wrap_method(
+ self.create_flow: gapic_v1.method_async.wrap_method(
self.create_flow,
default_timeout=None,
client_info=client_info,
),
- self.delete_flow: self._wrap_method(
+ self.delete_flow: gapic_v1.method_async.wrap_method(
self.delete_flow,
default_timeout=None,
client_info=client_info,
),
- self.list_flows: self._wrap_method(
+ self.list_flows: gapic_v1.method_async.wrap_method(
self.list_flows,
default_timeout=None,
client_info=client_info,
),
- self.get_flow: self._wrap_method(
+ self.get_flow: gapic_v1.method_async.wrap_method(
self.get_flow,
default_timeout=None,
client_info=client_info,
),
- self.update_flow: self._wrap_method(
+ self.update_flow: gapic_v1.method_async.wrap_method(
self.update_flow,
default_timeout=None,
client_info=client_info,
),
- self.train_flow: self._wrap_method(
+ self.train_flow: gapic_v1.method_async.wrap_method(
self.train_flow,
default_timeout=None,
client_info=client_info,
),
- self.validate_flow: self._wrap_method(
+ self.validate_flow: gapic_v1.method_async.wrap_method(
self.validate_flow,
default_timeout=None,
client_info=client_info,
),
- self.get_flow_validation_result: self._wrap_method(
+ self.get_flow_validation_result: gapic_v1.method_async.wrap_method(
self.get_flow_validation_result,
default_timeout=None,
client_info=client_info,
),
- self.import_flow: self._wrap_method(
+ self.import_flow: gapic_v1.method_async.wrap_method(
self.import_flow,
default_timeout=None,
client_info=client_info,
),
- self.export_flow: self._wrap_method(
+ self.export_flow: gapic_v1.method_async.wrap_method(
self.export_flow,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/rest.py
index 987a08adfb8f..066fd89a222d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/flows/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import flow
-from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseFlowsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import flow
+from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import FlowsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -462,8 +472,8 @@ class FlowsRestStub:
_interceptor: FlowsRestInterceptor
-class FlowsRestTransport(_BaseFlowsRestTransport):
- """REST backend synchronous transport for Flows.
+class FlowsRestTransport(FlowsTransport):
+ """REST backend transport for Flows.
Service for managing
[Flows][google.cloud.dialogflow.cx.v3beta1.Flow].
@@ -473,6 +483,7 @@ class FlowsRestTransport(_BaseFlowsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -526,12 +537,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -601,32 +621,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateFlow(_BaseFlowsRestTransport._BaseCreateFlow, FlowsRestStub):
+ class _CreateFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.CreateFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -676,34 +683,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseCreateFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/flows",
+ "body": "flow",
+ },
+ ]
request, metadata = self._interceptor.pre_create_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseCreateFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_flow.CreateFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseFlowsRestTransport._BaseCreateFlow._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseCreateFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._CreateFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -719,31 +737,19 @@ def __call__(
resp = self._interceptor.post_create_flow(resp)
return resp
- class _DeleteFlow(_BaseFlowsRestTransport._BaseDeleteFlow, FlowsRestStub):
+ class _DeleteFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.DeleteFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -766,29 +772,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = _BaseFlowsRestTransport._BaseDeleteFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseDeleteFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.DeleteFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseDeleteFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._DeleteFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -796,32 +811,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _ExportFlow(_BaseFlowsRestTransport._BaseExportFlow, FlowsRestStub):
+ class _ExportFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.ExportFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -851,34 +853,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseExportFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseExportFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.ExportFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseFlowsRestTransport._BaseExportFlow._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseExportFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._ExportFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -892,31 +905,19 @@ def __call__(
resp = self._interceptor.post_export_flow(resp)
return resp
- class _GetFlow(_BaseFlowsRestTransport._BaseGetFlow, FlowsRestStub):
+ class _GetFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.GetFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -966,27 +967,38 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseGetFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseGetFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.GetFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseFlowsRestTransport._BaseGetFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._GetFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1002,33 +1014,19 @@ def __call__(
resp = self._interceptor.post_get_flow(resp)
return resp
- class _GetFlowValidationResult(
- _BaseFlowsRestTransport._BaseGetFlowValidationResult, FlowsRestStub
- ):
+ class _GetFlowValidationResult(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.GetFlowValidationResult")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetFlowValidationResult")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1058,29 +1056,40 @@ def __call__(
"""
- http_options = (
- _BaseFlowsRestTransport._BaseGetFlowValidationResult._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/validationResult}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_flow_validation_result(
request, metadata
)
- transcoded_request = _BaseFlowsRestTransport._BaseGetFlowValidationResult._get_transcoded_request(
- http_options, request
- )
+ pb_request = flow.GetFlowValidationResultRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseFlowsRestTransport._BaseGetFlowValidationResult._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._GetFlowValidationResult._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1096,32 +1105,19 @@ def __call__(
resp = self._interceptor.post_get_flow_validation_result(resp)
return resp
- class _ImportFlow(_BaseFlowsRestTransport._BaseImportFlow, FlowsRestStub):
+ class _ImportFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.ImportFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ImportFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1151,34 +1147,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseImportFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/flows:import",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_import_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseImportFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.ImportFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseFlowsRestTransport._BaseImportFlow._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseImportFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._ImportFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1192,31 +1199,19 @@ def __call__(
resp = self._interceptor.post_import_flow(resp)
return resp
- class _ListFlows(_BaseFlowsRestTransport._BaseListFlows, FlowsRestStub):
+ class _ListFlows(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.ListFlows")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListFlows")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1245,29 +1240,38 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseListFlows._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/flows",
+ },
+ ]
request, metadata = self._interceptor.pre_list_flows(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseListFlows._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.ListFlowsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseListFlows._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._ListFlows._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1283,32 +1287,19 @@ def __call__(
resp = self._interceptor.post_list_flows(resp)
return resp
- class _TrainFlow(_BaseFlowsRestTransport._BaseTrainFlow, FlowsRestStub):
+ class _TrainFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.TrainFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("TrainFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1338,34 +1329,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseTrainFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}:train",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_train_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseTrainFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.TrainFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseFlowsRestTransport._BaseTrainFlow._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseTrainFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._TrainFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1379,32 +1381,19 @@ def __call__(
resp = self._interceptor.post_train_flow(resp)
return resp
- class _UpdateFlow(_BaseFlowsRestTransport._BaseUpdateFlow, FlowsRestStub):
+ class _UpdateFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.UpdateFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1454,34 +1443,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseUpdateFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{flow.name=projects/*/locations/*/agents/*/flows/*}",
+ "body": "flow",
+ },
+ ]
request, metadata = self._interceptor.pre_update_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseUpdateFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_flow.UpdateFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseFlowsRestTransport._BaseUpdateFlow._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseUpdateFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._UpdateFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1497,32 +1497,19 @@ def __call__(
resp = self._interceptor.post_update_flow(resp)
return resp
- class _ValidateFlow(_BaseFlowsRestTransport._BaseValidateFlow, FlowsRestStub):
+ class _ValidateFlow(FlowsRestStub):
def __hash__(self):
- return hash("FlowsRestTransport.ValidateFlow")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ValidateFlow")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1551,34 +1538,45 @@ def __call__(
"""
- http_options = _BaseFlowsRestTransport._BaseValidateFlow._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}:validate",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_validate_flow(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseValidateFlow._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = flow.ValidateFlowRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseFlowsRestTransport._BaseValidateFlow._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseValidateFlow._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = FlowsRestTransport._ValidateFlow._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1666,32 +1664,7 @@ def validate_flow(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseFlowsRestTransport._BaseGetLocation, FlowsRestStub):
- def __hash__(self):
- return hash("FlowsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(FlowsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1715,29 +1688,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = _BaseFlowsRestTransport._BaseGetLocation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = FlowsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1745,9 +1721,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1755,32 +1730,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(_BaseFlowsRestTransport._BaseListLocations, FlowsRestStub):
- def __hash__(self):
- return hash("FlowsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(FlowsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1804,31 +1754,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseFlowsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = FlowsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1836,9 +1787,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1846,32 +1796,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(_BaseFlowsRestTransport._BaseCancelOperation, FlowsRestStub):
- def __hash__(self):
- return hash("FlowsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(FlowsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1892,33 +1817,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseFlowsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = FlowsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1932,32 +1862,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseFlowsRestTransport._BaseGetOperation, FlowsRestStub):
- def __hash__(self):
- return hash("FlowsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(FlowsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1981,29 +1886,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = _BaseFlowsRestTransport._BaseGetOperation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = FlowsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2011,9 +1923,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -2021,32 +1932,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(_BaseFlowsRestTransport._BaseListOperations, FlowsRestStub):
- def __hash__(self):
- return hash("FlowsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(FlowsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -2070,31 +1956,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseFlowsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseFlowsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseFlowsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = FlowsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2102,9 +1993,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/async_client.py
index 3fca97193458..2b6af5c5037e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -188,7 +189,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = GeneratorsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(GeneratorsClient).get_transport_class, type(GeneratorsClient)
+ )
def __init__(
self,
@@ -370,8 +373,6 @@ async def sample_list_generators():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -861,7 +862,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -914,7 +919,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -970,7 +979,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1020,7 +1033,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1073,7 +1090,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/client.py
index 5cad82286fcd..31e954077c3d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/client.py
@@ -665,7 +665,7 @@ def __init__(
transport_init: Union[
Type[GeneratorsTransport], Callable[..., GeneratorsTransport]
] = (
- GeneratorsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., GeneratorsTransport], transport)
)
@@ -793,8 +793,6 @@ def sample_list_generators():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1285,7 +1283,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1338,7 +1340,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1394,7 +1400,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1444,7 +1454,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1497,7 +1511,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/pagers.py
index 5612c1cf5494..ed93ecf2de7d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import generator
@@ -65,8 +51,6 @@ def __init__(
request: generator.ListGeneratorsRequest,
response: generator.ListGeneratorsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListGeneratorsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = generator.ListGeneratorsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[generator.ListGeneratorsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[generator.Generator]:
@@ -139,8 +113,6 @@ def __init__(
request: generator.ListGeneratorsRequest,
response: generator.ListGeneratorsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListGeneratorsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = generator.ListGeneratorsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[generator.ListGeneratorsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[generator.Generator]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/base.py
index 452dbb15966a..78b919e03122 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -160,31 +158,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc.py
index 5eb7aa17dc3e..6a858b6ef065 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc_asyncio.py
index a1f24018e2ea..a58e9ffed06d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -387,70 +382,36 @@ def delete_generator(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_generators: self._wrap_method(
+ self.list_generators: gapic_v1.method_async.wrap_method(
self.list_generators,
default_timeout=None,
client_info=client_info,
),
- self.get_generator: self._wrap_method(
+ self.get_generator: gapic_v1.method_async.wrap_method(
self.get_generator,
default_timeout=None,
client_info=client_info,
),
- self.create_generator: self._wrap_method(
+ self.create_generator: gapic_v1.method_async.wrap_method(
self.create_generator,
default_timeout=None,
client_info=client_info,
),
- self.update_generator: self._wrap_method(
+ self.update_generator: gapic_v1.method_async.wrap_method(
self.update_generator,
default_timeout=None,
client_info=client_info,
),
- self.delete_generator: self._wrap_method(
+ self.delete_generator: gapic_v1.method_async.wrap_method(
self.delete_generator,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/rest.py
index 18d241961063..6e441f593e68 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/generators/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import generator
-from google.cloud.dialogflowcx_v3beta1.types import generator as gcdc_generator
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseGeneratorsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import generator
+from google.cloud.dialogflowcx_v3beta1.types import generator as gcdc_generator
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import GeneratorsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -329,8 +333,8 @@ class GeneratorsRestStub:
_interceptor: GeneratorsRestInterceptor
-class GeneratorsRestTransport(_BaseGeneratorsRestTransport):
- """REST backend synchronous transport for Generators.
+class GeneratorsRestTransport(GeneratorsTransport):
+ """REST backend transport for Generators.
Service for managing
[Generators][google.cloud.dialogflow.cx.v3beta1.Generator]
@@ -340,6 +344,7 @@ class GeneratorsRestTransport(_BaseGeneratorsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -393,12 +398,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -409,34 +423,19 @@ def __init__(
self._interceptor = interceptor or GeneratorsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateGenerator(
- _BaseGeneratorsRestTransport._BaseCreateGenerator, GeneratorsRestStub
- ):
+ class _CreateGenerator(GeneratorsRestStub):
def __hash__(self):
- return hash("GeneratorsRestTransport.CreateGenerator")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateGenerator")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -469,34 +468,47 @@ def __call__(
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseCreateGenerator._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/generators",
+ "body": "generator",
+ },
+ ]
request, metadata = self._interceptor.pre_create_generator(
request, metadata
)
- transcoded_request = _BaseGeneratorsRestTransport._BaseCreateGenerator._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_generator.CreateGeneratorRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseGeneratorsRestTransport._BaseCreateGenerator._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseGeneratorsRestTransport._BaseCreateGenerator._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = GeneratorsRestTransport._CreateGenerator._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -512,33 +524,19 @@ def __call__(
resp = self._interceptor.post_create_generator(resp)
return resp
- class _DeleteGenerator(
- _BaseGeneratorsRestTransport._BaseDeleteGenerator, GeneratorsRestStub
- ):
+ class _DeleteGenerator(GeneratorsRestStub):
def __hash__(self):
- return hash("GeneratorsRestTransport.DeleteGenerator")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteGenerator")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -561,29 +559,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseDeleteGenerator._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/generators/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_generator(
request, metadata
)
- transcoded_request = _BaseGeneratorsRestTransport._BaseDeleteGenerator._get_transcoded_request(
- http_options, request
- )
+ pb_request = generator.DeleteGeneratorRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseGeneratorsRestTransport._BaseDeleteGenerator._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = GeneratorsRestTransport._DeleteGenerator._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -591,33 +600,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetGenerator(
- _BaseGeneratorsRestTransport._BaseGetGenerator, GeneratorsRestStub
- ):
+ class _GetGenerator(GeneratorsRestStub):
def __hash__(self):
- return hash("GeneratorsRestTransport.GetGenerator")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetGenerator")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -650,31 +645,38 @@ def __call__(
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseGetGenerator._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/generators/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_generator(request, metadata)
- transcoded_request = (
- _BaseGeneratorsRestTransport._BaseGetGenerator._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = generator.GetGeneratorRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseGetGenerator._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = GeneratorsRestTransport._GetGenerator._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -690,33 +692,19 @@ def __call__(
resp = self._interceptor.post_get_generator(resp)
return resp
- class _ListGenerators(
- _BaseGeneratorsRestTransport._BaseListGenerators, GeneratorsRestStub
- ):
+ class _ListGenerators(GeneratorsRestStub):
def __hash__(self):
- return hash("GeneratorsRestTransport.ListGenerators")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListGenerators")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -745,29 +733,38 @@ def __call__(
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseListGenerators._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/generators",
+ },
+ ]
request, metadata = self._interceptor.pre_list_generators(request, metadata)
- transcoded_request = _BaseGeneratorsRestTransport._BaseListGenerators._get_transcoded_request(
- http_options, request
- )
+ pb_request = generator.ListGeneratorsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseListGenerators._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = GeneratorsRestTransport._ListGenerators._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -783,34 +780,19 @@ def __call__(
resp = self._interceptor.post_list_generators(resp)
return resp
- class _UpdateGenerator(
- _BaseGeneratorsRestTransport._BaseUpdateGenerator, GeneratorsRestStub
- ):
+ class _UpdateGenerator(GeneratorsRestStub):
def __hash__(self):
- return hash("GeneratorsRestTransport.UpdateGenerator")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateGenerator")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -843,34 +825,47 @@ def __call__(
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseUpdateGenerator._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{generator.name=projects/*/locations/*/agents/*/generators/*}",
+ "body": "generator",
+ },
+ ]
request, metadata = self._interceptor.pre_update_generator(
request, metadata
)
- transcoded_request = _BaseGeneratorsRestTransport._BaseUpdateGenerator._get_transcoded_request(
- http_options, request
- )
+ pb_request = gcdc_generator.UpdateGeneratorRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseGeneratorsRestTransport._BaseUpdateGenerator._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseGeneratorsRestTransport._BaseUpdateGenerator._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = GeneratorsRestTransport._UpdateGenerator._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -930,34 +925,7 @@ def update_generator(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseGeneratorsRestTransport._BaseGetLocation, GeneratorsRestStub
- ):
- def __hash__(self):
- return hash("GeneratorsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(GeneratorsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -981,31 +949,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseGeneratorsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = GeneratorsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1013,9 +982,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1023,34 +991,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseGeneratorsRestTransport._BaseListLocations, GeneratorsRestStub
- ):
- def __hash__(self):
- return hash("GeneratorsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(GeneratorsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1074,31 +1015,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseGeneratorsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = GeneratorsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1106,9 +1048,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1116,34 +1057,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseGeneratorsRestTransport._BaseCancelOperation, GeneratorsRestStub
- ):
- def __hash__(self):
- return hash("GeneratorsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(GeneratorsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1164,29 +1078,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseGeneratorsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseGeneratorsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = GeneratorsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1200,34 +1123,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseGeneratorsRestTransport._BaseGetOperation, GeneratorsRestStub
- ):
- def __hash__(self):
- return hash("GeneratorsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(GeneratorsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1251,31 +1147,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseGeneratorsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = GeneratorsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1283,9 +1184,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1293,34 +1193,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseGeneratorsRestTransport._BaseListOperations, GeneratorsRestStub
- ):
- def __hash__(self):
- return hash("GeneratorsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(GeneratorsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1344,29 +1217,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseGeneratorsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseGeneratorsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseGeneratorsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = GeneratorsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1374,9 +1254,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py
index ef3ca1d10ca7..971318cfcac1 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -189,7 +190,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = IntentsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(IntentsClient).get_transport_class, type(IntentsClient)
+ )
def __init__(
self,
@@ -371,8 +374,6 @@ async def sample_list_intents():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1094,7 +1095,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1147,7 +1152,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1203,7 +1212,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1253,7 +1266,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1306,7 +1323,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/client.py
index 0e8b09b6b1ff..c78481c581f0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/client.py
@@ -690,7 +690,7 @@ def __init__(
transport_init: Union[
Type[IntentsTransport], Callable[..., IntentsTransport]
] = (
- IntentsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., IntentsTransport], transport)
)
@@ -818,8 +818,6 @@ def sample_list_intents():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1538,7 +1536,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1591,7 +1593,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1647,7 +1653,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1697,7 +1707,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1750,7 +1764,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py
index 2338ee007dfe..1f793af6d625 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import intent
@@ -65,8 +51,6 @@ def __init__(
request: intent.ListIntentsRequest,
response: intent.ListIntentsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListIntentsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = intent.ListIntentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[intent.ListIntentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[intent.Intent]:
@@ -139,8 +113,6 @@ def __init__(
request: intent.ListIntentsRequest,
response: intent.ListIntentsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListIntentsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = intent.ListIntentsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[intent.Intent]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py
index 1cc2fec5dfed..b2041c32029e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -170,31 +168,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py
index 137b62907b01..9031a276ef24 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py
index 36f7db859b96..0c24df5a1e58 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -482,80 +477,46 @@ def export_intents(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_intents: self._wrap_method(
+ self.list_intents: gapic_v1.method_async.wrap_method(
self.list_intents,
default_timeout=None,
client_info=client_info,
),
- self.get_intent: self._wrap_method(
+ self.get_intent: gapic_v1.method_async.wrap_method(
self.get_intent,
default_timeout=None,
client_info=client_info,
),
- self.create_intent: self._wrap_method(
+ self.create_intent: gapic_v1.method_async.wrap_method(
self.create_intent,
default_timeout=None,
client_info=client_info,
),
- self.update_intent: self._wrap_method(
+ self.update_intent: gapic_v1.method_async.wrap_method(
self.update_intent,
default_timeout=None,
client_info=client_info,
),
- self.delete_intent: self._wrap_method(
+ self.delete_intent: gapic_v1.method_async.wrap_method(
self.delete_intent,
default_timeout=None,
client_info=client_info,
),
- self.import_intents: self._wrap_method(
+ self.import_intents: gapic_v1.method_async.wrap_method(
self.import_intents,
default_timeout=None,
client_info=client_info,
),
- self.export_intents: self._wrap_method(
+ self.export_intents: gapic_v1.method_async.wrap_method(
self.export_intents,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/rest.py
index c36151c1ef81..962ce77c65ed 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/intents/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import intent
-from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseIntentsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import intent
+from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import IntentsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -377,8 +387,8 @@ class IntentsRestStub:
_interceptor: IntentsRestInterceptor
-class IntentsRestTransport(_BaseIntentsRestTransport):
- """REST backend synchronous transport for Intents.
+class IntentsRestTransport(IntentsTransport):
+ """REST backend transport for Intents.
Service for managing
[Intents][google.cloud.dialogflow.cx.v3beta1.Intent].
@@ -388,6 +398,7 @@ class IntentsRestTransport(_BaseIntentsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -441,12 +452,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -516,32 +536,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateIntent(_BaseIntentsRestTransport._BaseCreateIntent, IntentsRestStub):
+ class _CreateIntent(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.CreateIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -575,36 +582,45 @@ def __call__(
"""
- http_options = (
- _BaseIntentsRestTransport._BaseCreateIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/intents",
+ "body": "intent",
+ },
+ ]
request, metadata = self._interceptor.pre_create_intent(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseCreateIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_intent.CreateIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseIntentsRestTransport._BaseCreateIntent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseCreateIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._CreateIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -620,31 +636,19 @@ def __call__(
resp = self._interceptor.post_create_intent(resp)
return resp
- class _DeleteIntent(_BaseIntentsRestTransport._BaseDeleteIntent, IntentsRestStub):
+ class _DeleteIntent(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.DeleteIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -667,31 +671,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseDeleteIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/intents/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_intent(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseDeleteIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = intent.DeleteIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseDeleteIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._DeleteIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -699,32 +710,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _ExportIntents(_BaseIntentsRestTransport._BaseExportIntents, IntentsRestStub):
+ class _ExportIntents(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.ExportIntents")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportIntents")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -754,36 +752,45 @@ def __call__(
"""
- http_options = (
- _BaseIntentsRestTransport._BaseExportIntents._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/intents:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_intents(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseExportIntents._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = intent.ExportIntentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseIntentsRestTransport._BaseExportIntents._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseExportIntents._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._ExportIntents._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -797,31 +804,19 @@ def __call__(
resp = self._interceptor.post_export_intents(resp)
return resp
- class _GetIntent(_BaseIntentsRestTransport._BaseGetIntent, IntentsRestStub):
+ class _GetIntent(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.GetIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -855,29 +850,38 @@ def __call__(
"""
- http_options = _BaseIntentsRestTransport._BaseGetIntent._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/intents/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_intent(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseGetIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = intent.GetIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseGetIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._GetIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -893,32 +897,19 @@ def __call__(
resp = self._interceptor.post_get_intent(resp)
return resp
- class _ImportIntents(_BaseIntentsRestTransport._BaseImportIntents, IntentsRestStub):
+ class _ImportIntents(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.ImportIntents")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ImportIntents")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -948,36 +939,45 @@ def __call__(
"""
- http_options = (
- _BaseIntentsRestTransport._BaseImportIntents._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/intents:import",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_import_intents(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseImportIntents._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = intent.ImportIntentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseIntentsRestTransport._BaseImportIntents._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseImportIntents._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._ImportIntents._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -991,31 +991,19 @@ def __call__(
resp = self._interceptor.post_import_intents(resp)
return resp
- class _ListIntents(_BaseIntentsRestTransport._BaseListIntents, IntentsRestStub):
+ class _ListIntents(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.ListIntents")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListIntents")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1044,31 +1032,38 @@ def __call__(
"""
- http_options = (
- _BaseIntentsRestTransport._BaseListIntents._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/intents",
+ },
+ ]
request, metadata = self._interceptor.pre_list_intents(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseListIntents._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = intent.ListIntentsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseListIntents._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._ListIntents._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1084,32 +1079,19 @@ def __call__(
resp = self._interceptor.post_list_intents(resp)
return resp
- class _UpdateIntent(_BaseIntentsRestTransport._BaseUpdateIntent, IntentsRestStub):
+ class _UpdateIntent(IntentsRestStub):
def __hash__(self):
- return hash("IntentsRestTransport.UpdateIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1143,36 +1125,45 @@ def __call__(
"""
- http_options = (
- _BaseIntentsRestTransport._BaseUpdateIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{intent.name=projects/*/locations/*/agents/*/intents/*}",
+ "body": "intent",
+ },
+ ]
request, metadata = self._interceptor.pre_update_intent(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseUpdateIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_intent.UpdateIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseIntentsRestTransport._BaseUpdateIntent._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseUpdateIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = IntentsRestTransport._UpdateIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1244,32 +1235,7 @@ def update_intent(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseIntentsRestTransport._BaseGetLocation, IntentsRestStub):
- def __hash__(self):
- return hash("IntentsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(IntentsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1293,31 +1259,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = IntentsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1325,9 +1292,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1335,32 +1301,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(_BaseIntentsRestTransport._BaseListLocations, IntentsRestStub):
- def __hash__(self):
- return hash("IntentsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(IntentsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1384,31 +1325,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = IntentsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1416,9 +1358,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1426,34 +1367,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseIntentsRestTransport._BaseCancelOperation, IntentsRestStub
- ):
- def __hash__(self):
- return hash("IntentsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(IntentsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1474,33 +1388,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = IntentsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1514,32 +1433,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseIntentsRestTransport._BaseGetOperation, IntentsRestStub):
- def __hash__(self):
- return hash("IntentsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(IntentsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1563,31 +1457,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = IntentsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1595,9 +1494,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1605,34 +1503,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseIntentsRestTransport._BaseListOperations, IntentsRestStub
- ):
- def __hash__(self):
- return hash("IntentsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(IntentsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1656,31 +1527,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseIntentsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseIntentsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseIntentsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = IntentsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1688,9 +1564,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py
index bc373f6b2363..a586118402d4 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -78,8 +79,6 @@ class PagesAsyncClient:
parse_intent_path = staticmethod(PagesClient.parse_intent_path)
page_path = staticmethod(PagesClient.page_path)
parse_page_path = staticmethod(PagesClient.parse_page_path)
- playbook_path = staticmethod(PagesClient.playbook_path)
- parse_playbook_path = staticmethod(PagesClient.parse_playbook_path)
tool_path = staticmethod(PagesClient.tool_path)
parse_tool_path = staticmethod(PagesClient.parse_tool_path)
transition_route_group_path = staticmethod(PagesClient.transition_route_group_path)
@@ -200,7 +199,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = PagesClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(PagesClient).get_transport_class, type(PagesClient)
+ )
def __init__(
self,
@@ -381,8 +382,6 @@ async def sample_list_pages():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -916,7 +915,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -969,7 +972,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1025,7 +1032,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1075,7 +1086,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1128,7 +1143,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/client.py
index a50c36358195..81147a8ff58e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/client.py
@@ -287,30 +287,6 @@ def parse_page_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
- @staticmethod
- def playbook_path(
- project: str,
- location: str,
- agent: str,
- playbook: str,
- ) -> str:
- """Returns a fully-qualified playbook string."""
- return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
- project=project,
- location=location,
- agent=agent,
- playbook=playbook,
- )
-
- @staticmethod
- def parse_playbook_path(path: str) -> Dict[str, str]:
- """Parses a playbook path into its component segments."""
- m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$",
- path,
- )
- return m.groupdict() if m else {}
-
@staticmethod
def tool_path(
project: str,
@@ -837,7 +813,7 @@ def __init__(
transport_init: Union[
Type[PagesTransport], Callable[..., PagesTransport]
] = (
- PagesClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., PagesTransport], transport)
)
@@ -964,8 +940,6 @@ def sample_list_pages():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1502,7 +1476,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1555,7 +1533,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1611,7 +1593,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1661,7 +1647,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1714,7 +1704,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py
index 0d59523dd3f3..4b968769fbae 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import page
@@ -65,8 +51,6 @@ def __init__(
request: page.ListPagesRequest,
response: page.ListPagesResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = page.ListPagesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[page.ListPagesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[page.Page]:
@@ -139,8 +113,6 @@ def __init__(
request: page.ListPagesRequest,
response: page.ListPagesResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = page.ListPagesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[page.ListPagesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[page.Page]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py
index a14eb2b534f4..bcfdca558c7c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -160,31 +158,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py
index 230146ac4faf..c2a80bc63639 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py
index 118b327d758e..edab4b7636fe 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -378,70 +373,36 @@ def delete_page(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_pages: self._wrap_method(
+ self.list_pages: gapic_v1.method_async.wrap_method(
self.list_pages,
default_timeout=None,
client_info=client_info,
),
- self.get_page: self._wrap_method(
+ self.get_page: gapic_v1.method_async.wrap_method(
self.get_page,
default_timeout=None,
client_info=client_info,
),
- self.create_page: self._wrap_method(
+ self.create_page: gapic_v1.method_async.wrap_method(
self.create_page,
default_timeout=None,
client_info=client_info,
),
- self.update_page: self._wrap_method(
+ self.update_page: gapic_v1.method_async.wrap_method(
self.update_page,
default_timeout=None,
client_info=client_info,
),
- self.delete_page: self._wrap_method(
+ self.delete_page: gapic_v1.method_async.wrap_method(
self.delete_page,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/rest.py
index 835b1298129d..38027df3cfcc 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/pages/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import page
-from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BasePagesRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import page
+from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import PagesTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -315,8 +319,8 @@ class PagesRestStub:
_interceptor: PagesRestInterceptor
-class PagesRestTransport(_BasePagesRestTransport):
- """REST backend synchronous transport for Pages.
+class PagesRestTransport(PagesTransport):
+ """REST backend transport for Pages.
Service for managing
[Pages][google.cloud.dialogflow.cx.v3beta1.Page].
@@ -326,6 +330,7 @@ class PagesRestTransport(_BasePagesRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -379,12 +384,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -395,32 +409,19 @@ def __init__(
self._interceptor = interceptor or PagesRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreatePage(_BasePagesRestTransport._BaseCreatePage, PagesRestStub):
+ class _CreatePage(PagesRestStub):
def __hash__(self):
- return hash("PagesRestTransport.CreatePage")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreatePage")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -468,34 +469,45 @@ def __call__(
"""
- http_options = _BasePagesRestTransport._BaseCreatePage._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/pages",
+ "body": "page",
+ },
+ ]
request, metadata = self._interceptor.pre_create_page(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseCreatePage._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_page.CreatePageRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BasePagesRestTransport._BaseCreatePage._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseCreatePage._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PagesRestTransport._CreatePage._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -511,31 +523,19 @@ def __call__(
resp = self._interceptor.post_create_page(resp)
return resp
- class _DeletePage(_BasePagesRestTransport._BaseDeletePage, PagesRestStub):
+ class _DeletePage(PagesRestStub):
def __hash__(self):
- return hash("PagesRestTransport.DeletePage")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeletePage")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -558,29 +558,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = _BasePagesRestTransport._BaseDeletePage._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/pages/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_page(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseDeletePage._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = page.DeletePageRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseDeletePage._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PagesRestTransport._DeletePage._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -588,31 +597,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetPage(_BasePagesRestTransport._BaseGetPage, PagesRestStub):
+ class _GetPage(PagesRestStub):
def __hash__(self):
- return hash("PagesRestTransport.GetPage")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetPage")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -660,27 +657,38 @@ def __call__(
"""
- http_options = _BasePagesRestTransport._BaseGetPage._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/pages/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_page(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseGetPage._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = page.GetPageRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BasePagesRestTransport._BaseGetPage._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PagesRestTransport._GetPage._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -696,31 +704,19 @@ def __call__(
resp = self._interceptor.post_get_page(resp)
return resp
- class _ListPages(_BasePagesRestTransport._BaseListPages, PagesRestStub):
+ class _ListPages(PagesRestStub):
def __hash__(self):
- return hash("PagesRestTransport.ListPages")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListPages")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -749,29 +745,38 @@ def __call__(
"""
- http_options = _BasePagesRestTransport._BaseListPages._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/pages",
+ },
+ ]
request, metadata = self._interceptor.pre_list_pages(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseListPages._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = page.ListPagesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseListPages._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PagesRestTransport._ListPages._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -787,32 +792,19 @@ def __call__(
resp = self._interceptor.post_list_pages(resp)
return resp
- class _UpdatePage(_BasePagesRestTransport._BaseUpdatePage, PagesRestStub):
+ class _UpdatePage(PagesRestStub):
def __hash__(self):
- return hash("PagesRestTransport.UpdatePage")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdatePage")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -860,34 +852,45 @@ def __call__(
"""
- http_options = _BasePagesRestTransport._BaseUpdatePage._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{page.name=projects/*/locations/*/agents/*/flows/*/pages/*}",
+ "body": "page",
+ },
+ ]
request, metadata = self._interceptor.pre_update_page(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseUpdatePage._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_page.UpdatePageRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BasePagesRestTransport._BaseUpdatePage._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseUpdatePage._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PagesRestTransport._UpdatePage._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -937,32 +940,7 @@ def update_page(self) -> Callable[[gcdc_page.UpdatePageRequest], gcdc_page.Page]
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BasePagesRestTransport._BaseGetLocation, PagesRestStub):
- def __hash__(self):
- return hash("PagesRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(PagesRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -986,29 +964,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = _BasePagesRestTransport._BaseGetLocation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PagesRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1016,9 +997,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1026,32 +1006,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(_BasePagesRestTransport._BaseListLocations, PagesRestStub):
- def __hash__(self):
- return hash("PagesRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(PagesRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1075,31 +1030,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BasePagesRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PagesRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1107,9 +1063,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1117,32 +1072,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(_BasePagesRestTransport._BaseCancelOperation, PagesRestStub):
- def __hash__(self):
- return hash("PagesRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(PagesRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1163,33 +1093,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BasePagesRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BasePagesRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PagesRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1203,32 +1138,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BasePagesRestTransport._BaseGetOperation, PagesRestStub):
- def __hash__(self):
- return hash("PagesRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(PagesRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1252,29 +1162,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = _BasePagesRestTransport._BaseGetOperation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PagesRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1282,9 +1199,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1292,32 +1208,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(_BasePagesRestTransport._BaseListOperations, PagesRestStub):
- def __hash__(self):
- return hash("PagesRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(PagesRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1341,31 +1232,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BasePagesRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BasePagesRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePagesRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PagesRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1373,9 +1269,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/async_client.py
index 7039e1388332..891af3a309db 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -203,7 +204,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = PlaybooksClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(PlaybooksClient).get_transport_class, type(PlaybooksClient)
+ )
def __init__(
self,
@@ -608,8 +611,6 @@ async def sample_list_playbooks():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1200,8 +1201,6 @@ async def sample_list_playbook_versions():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1334,7 +1333,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1387,7 +1390,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1443,7 +1450,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1493,7 +1504,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1546,7 +1561,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/client.py
index 9dd23db08a84..294498d0b381 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/client.py
@@ -770,7 +770,7 @@ def __init__(
transport_init: Union[
Type[PlaybooksTransport], Callable[..., PlaybooksTransport]
] = (
- PlaybooksClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., PlaybooksTransport], transport)
)
@@ -1115,8 +1115,6 @@ def sample_list_playbooks():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1692,8 +1690,6 @@ def sample_list_playbook_versions():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1836,7 +1832,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1889,7 +1889,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1945,7 +1949,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1995,7 +2003,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2048,7 +2060,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/pagers.py
index e4aa129e6fe8..d60a58dbe8a0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import playbook
@@ -65,8 +51,6 @@ def __init__(
request: playbook.ListPlaybooksRequest,
response: playbook.ListPlaybooksResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPlaybooksResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = playbook.ListPlaybooksRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[playbook.ListPlaybooksResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[playbook.Playbook]:
@@ -139,8 +113,6 @@ def __init__(
request: playbook.ListPlaybooksRequest,
response: playbook.ListPlaybooksResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPlaybooksResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = playbook.ListPlaybooksRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[playbook.ListPlaybooksResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[playbook.Playbook]:
@@ -217,8 +179,6 @@ def __init__(
request: playbook.ListPlaybookVersionsRequest,
response: playbook.ListPlaybookVersionsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -230,17 +190,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPlaybookVersionsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = playbook.ListPlaybookVersionsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -251,12 +206,7 @@ def pages(self) -> Iterator[playbook.ListPlaybookVersionsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[playbook.PlaybookVersion]:
@@ -291,8 +241,6 @@ def __init__(
request: playbook.ListPlaybookVersionsRequest,
response: playbook.ListPlaybookVersionsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -304,17 +252,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListPlaybookVersionsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = playbook.ListPlaybookVersionsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -325,12 +268,7 @@ async def pages(self) -> AsyncIterator[playbook.ListPlaybookVersionsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[playbook.PlaybookVersion]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/base.py
index 53caad269957..c2d7e757559b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -180,31 +178,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc.py
index 0dd4d38668c9..5243f7a14b49 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc_asyncio.py
index 5b2c85d222bb..15c955a5c5e9 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -497,90 +492,56 @@ def delete_playbook_version(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.create_playbook: self._wrap_method(
+ self.create_playbook: gapic_v1.method_async.wrap_method(
self.create_playbook,
default_timeout=None,
client_info=client_info,
),
- self.delete_playbook: self._wrap_method(
+ self.delete_playbook: gapic_v1.method_async.wrap_method(
self.delete_playbook,
default_timeout=None,
client_info=client_info,
),
- self.list_playbooks: self._wrap_method(
+ self.list_playbooks: gapic_v1.method_async.wrap_method(
self.list_playbooks,
default_timeout=None,
client_info=client_info,
),
- self.get_playbook: self._wrap_method(
+ self.get_playbook: gapic_v1.method_async.wrap_method(
self.get_playbook,
default_timeout=None,
client_info=client_info,
),
- self.update_playbook: self._wrap_method(
+ self.update_playbook: gapic_v1.method_async.wrap_method(
self.update_playbook,
default_timeout=None,
client_info=client_info,
),
- self.create_playbook_version: self._wrap_method(
+ self.create_playbook_version: gapic_v1.method_async.wrap_method(
self.create_playbook_version,
default_timeout=None,
client_info=client_info,
),
- self.get_playbook_version: self._wrap_method(
+ self.get_playbook_version: gapic_v1.method_async.wrap_method(
self.get_playbook_version,
default_timeout=None,
client_info=client_info,
),
- self.list_playbook_versions: self._wrap_method(
+ self.list_playbook_versions: gapic_v1.method_async.wrap_method(
self.list_playbook_versions,
default_timeout=None,
client_info=client_info,
),
- self.delete_playbook_version: self._wrap_method(
+ self.delete_playbook_version: gapic_v1.method_async.wrap_method(
self.delete_playbook_version,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/rest.py
index 556b3ea4925e..ca6ef7f5b7f0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/playbooks/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import playbook
-from google.cloud.dialogflowcx_v3beta1.types import playbook as gcdc_playbook
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BasePlaybooksRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import playbook
+from google.cloud.dialogflowcx_v3beta1.types import playbook as gcdc_playbook
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import PlaybooksTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -436,8 +440,8 @@ class PlaybooksRestStub:
_interceptor: PlaybooksRestInterceptor
-class PlaybooksRestTransport(_BasePlaybooksRestTransport):
- """REST backend synchronous transport for Playbooks.
+class PlaybooksRestTransport(PlaybooksTransport):
+ """REST backend transport for Playbooks.
Service for managing
[Playbooks][google.cloud.dialogflow.cx.v3beta1.Playbook].
@@ -447,6 +451,7 @@ class PlaybooksRestTransport(_BasePlaybooksRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -500,12 +505,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -516,34 +530,19 @@ def __init__(
self._interceptor = interceptor or PlaybooksRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreatePlaybook(
- _BasePlaybooksRestTransport._BaseCreatePlaybook, PlaybooksRestStub
- ):
+ class _CreatePlaybook(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.CreatePlaybook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreatePlaybook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -583,38 +582,45 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseCreatePlaybook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/playbooks",
+ "body": "playbook",
+ },
+ ]
request, metadata = self._interceptor.pre_create_playbook(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseCreatePlaybook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_playbook.CreatePlaybookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BasePlaybooksRestTransport._BaseCreatePlaybook._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseCreatePlaybook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._CreatePlaybook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -630,34 +636,19 @@ def __call__(
resp = self._interceptor.post_create_playbook(resp)
return resp
- class _CreatePlaybookVersion(
- _BasePlaybooksRestTransport._BaseCreatePlaybookVersion, PlaybooksRestStub
- ):
+ class _CreatePlaybookVersion(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.CreatePlaybookVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreatePlaybookVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -686,34 +677,47 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions",
+ "body": "playbook_version",
+ },
+ ]
request, metadata = self._interceptor.pre_create_playbook_version(
request, metadata
)
- transcoded_request = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_transcoded_request(
- http_options, request
- )
+ pb_request = playbook.CreatePlaybookVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._CreatePlaybookVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -729,33 +733,19 @@ def __call__(
resp = self._interceptor.post_create_playbook_version(resp)
return resp
- class _DeletePlaybook(
- _BasePlaybooksRestTransport._BaseDeletePlaybook, PlaybooksRestStub
- ):
+ class _DeletePlaybook(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.DeletePlaybook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeletePlaybook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -778,31 +768,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseDeletePlaybook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_playbook(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseDeletePlaybook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = playbook.DeletePlaybookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseDeletePlaybook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._DeletePlaybook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -810,33 +807,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _DeletePlaybookVersion(
- _BasePlaybooksRestTransport._BaseDeletePlaybookVersion, PlaybooksRestStub
- ):
+ class _DeletePlaybookVersion(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.DeletePlaybookVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeletePlaybookVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -859,29 +842,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_playbook_version(
request, metadata
)
- transcoded_request = _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_transcoded_request(
- http_options, request
- )
+ pb_request = playbook.DeletePlaybookVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._DeletePlaybookVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -889,31 +883,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetPlaybook(_BasePlaybooksRestTransport._BaseGetPlaybook, PlaybooksRestStub):
+ class _GetPlaybook(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.GetPlaybook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetPlaybook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -953,31 +935,38 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseGetPlaybook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_playbook(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseGetPlaybook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = playbook.GetPlaybookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseGetPlaybook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._GetPlaybook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -993,33 +982,19 @@ def __call__(
resp = self._interceptor.post_get_playbook(resp)
return resp
- class _GetPlaybookVersion(
- _BasePlaybooksRestTransport._BaseGetPlaybookVersion, PlaybooksRestStub
- ):
+ class _GetPlaybookVersion(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.GetPlaybookVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetPlaybookVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1048,29 +1023,40 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_playbook_version(
request, metadata
)
- transcoded_request = _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_transcoded_request(
- http_options, request
- )
+ pb_request = playbook.GetPlaybookVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._GetPlaybookVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1086,33 +1072,19 @@ def __call__(
resp = self._interceptor.post_get_playbook_version(resp)
return resp
- class _ListPlaybooks(
- _BasePlaybooksRestTransport._BaseListPlaybooks, PlaybooksRestStub
- ):
+ class _ListPlaybooks(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.ListPlaybooks")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListPlaybooks")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1141,31 +1113,38 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseListPlaybooks._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/playbooks",
+ },
+ ]
request, metadata = self._interceptor.pre_list_playbooks(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseListPlaybooks._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = playbook.ListPlaybooksRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseListPlaybooks._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._ListPlaybooks._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1181,33 +1160,19 @@ def __call__(
resp = self._interceptor.post_list_playbooks(resp)
return resp
- class _ListPlaybookVersions(
- _BasePlaybooksRestTransport._BaseListPlaybookVersions, PlaybooksRestStub
- ):
+ class _ListPlaybookVersions(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.ListPlaybookVersions")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListPlaybookVersions")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1236,29 +1201,40 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions",
+ },
+ ]
request, metadata = self._interceptor.pre_list_playbook_versions(
request, metadata
)
- transcoded_request = _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_transcoded_request(
- http_options, request
- )
+ pb_request = playbook.ListPlaybookVersionsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._ListPlaybookVersions._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1274,34 +1250,19 @@ def __call__(
resp = self._interceptor.post_list_playbook_versions(resp)
return resp
- class _UpdatePlaybook(
- _BasePlaybooksRestTransport._BaseUpdatePlaybook, PlaybooksRestStub
- ):
+ class _UpdatePlaybook(PlaybooksRestStub):
def __hash__(self):
- return hash("PlaybooksRestTransport.UpdatePlaybook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdatePlaybook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1341,38 +1302,45 @@ def __call__(
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{playbook.name=projects/*/locations/*/agents/*/playbooks/*}",
+ "body": "playbook",
+ },
+ ]
request, metadata = self._interceptor.pre_update_playbook(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_playbook.UpdatePlaybookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = PlaybooksRestTransport._UpdatePlaybook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1466,32 +1434,7 @@ def update_playbook(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BasePlaybooksRestTransport._BaseGetLocation, PlaybooksRestStub):
- def __hash__(self):
- return hash("PlaybooksRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(PlaybooksRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1515,31 +1458,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PlaybooksRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1547,9 +1491,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1557,34 +1500,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BasePlaybooksRestTransport._BaseListLocations, PlaybooksRestStub
- ):
- def __hash__(self):
- return hash("PlaybooksRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(PlaybooksRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1608,31 +1524,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PlaybooksRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1640,9 +1557,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1650,34 +1566,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BasePlaybooksRestTransport._BaseCancelOperation, PlaybooksRestStub
- ):
- def __hash__(self):
- return hash("PlaybooksRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(PlaybooksRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1698,31 +1587,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BasePlaybooksRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PlaybooksRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1736,34 +1632,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BasePlaybooksRestTransport._BaseGetOperation, PlaybooksRestStub
- ):
- def __hash__(self):
- return hash("PlaybooksRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(PlaybooksRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1787,31 +1656,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PlaybooksRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1819,9 +1693,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1829,34 +1702,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BasePlaybooksRestTransport._BaseListOperations, PlaybooksRestStub
- ):
- def __hash__(self):
- return hash("PlaybooksRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(PlaybooksRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1880,31 +1726,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BasePlaybooksRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BasePlaybooksRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BasePlaybooksRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = PlaybooksRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1912,9 +1763,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py
index 2bd5621c2d25..92f826d34c53 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -215,7 +216,10 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = SecuritySettingsServiceClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(SecuritySettingsServiceClient).get_transport_class,
+ type(SecuritySettingsServiceClient),
+ )
def __init__(
self,
@@ -781,8 +785,6 @@ async def sample_list_security_settings():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -919,7 +921,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -972,7 +978,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1028,7 +1038,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1078,7 +1092,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1131,7 +1149,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py
index 0cd1f988e46b..7d84882c7f37 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py
@@ -720,7 +720,7 @@ def __init__(
Type[SecuritySettingsServiceTransport],
Callable[..., SecuritySettingsServiceTransport],
] = (
- SecuritySettingsServiceClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., SecuritySettingsServiceTransport], transport)
)
@@ -1219,8 +1219,6 @@ def sample_list_security_settings():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1367,7 +1365,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1420,7 +1422,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1476,7 +1482,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1526,7 +1536,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1579,7 +1593,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py
index 5493fed926a5..8b952dc49d87 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import security_settings
@@ -65,8 +51,6 @@ def __init__(
request: security_settings.ListSecuritySettingsRequest,
response: security_settings.ListSecuritySettingsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = security_settings.ListSecuritySettingsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[security_settings.ListSecuritySettingsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[security_settings.SecuritySettings]:
@@ -141,8 +115,6 @@ def __init__(
request: security_settings.ListSecuritySettingsRequest,
response: security_settings.ListSecuritySettingsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -154,17 +126,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = security_settings.ListSecuritySettingsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -177,12 +144,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[security_settings.SecuritySettings]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py
index bab3a1194047..8f597411a793 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py
@@ -90,8 +90,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -104,7 +102,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -162,31 +160,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py
index 718444f22c58..64bc817a9e03 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py
index 8b82abadecb3..aeecc0718f43 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -400,70 +395,36 @@ def delete_security_settings(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.create_security_settings: self._wrap_method(
+ self.create_security_settings: gapic_v1.method_async.wrap_method(
self.create_security_settings,
default_timeout=None,
client_info=client_info,
),
- self.get_security_settings: self._wrap_method(
+ self.get_security_settings: gapic_v1.method_async.wrap_method(
self.get_security_settings,
default_timeout=None,
client_info=client_info,
),
- self.update_security_settings: self._wrap_method(
+ self.update_security_settings: gapic_v1.method_async.wrap_method(
self.update_security_settings,
default_timeout=None,
client_info=client_info,
),
- self.list_security_settings: self._wrap_method(
+ self.list_security_settings: gapic_v1.method_async.wrap_method(
self.list_security_settings,
default_timeout=None,
client_info=client_info,
),
- self.delete_security_settings: self._wrap_method(
+ self.delete_security_settings: gapic_v1.method_async.wrap_method(
self.delete_security_settings,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/rest.py
index 2eb7691b78b0..466e8ebdc7d0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/rest.py
@@ -16,33 +16,37 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+
+
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
from google.cloud.dialogflowcx_v3beta1.types import (
security_settings as gcdc_security_settings,
)
from google.cloud.dialogflowcx_v3beta1.types import security_settings
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseSecuritySettingsServiceRestTransport
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
-
+from .base import SecuritySettingsServiceTransport
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
@@ -341,8 +345,8 @@ class SecuritySettingsServiceRestStub:
_interceptor: SecuritySettingsServiceRestInterceptor
-class SecuritySettingsServiceRestTransport(_BaseSecuritySettingsServiceRestTransport):
- """REST backend synchronous transport for SecuritySettingsService.
+class SecuritySettingsServiceRestTransport(SecuritySettingsServiceTransport):
+ """REST backend transport for SecuritySettingsService.
Service for managing security settings for Dialogflow.
@@ -351,6 +355,7 @@ class SecuritySettingsServiceRestTransport(_BaseSecuritySettingsServiceRestTrans
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -404,12 +409,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -420,35 +434,19 @@ def __init__(
self._interceptor = interceptor or SecuritySettingsServiceRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateSecuritySettings(
- _BaseSecuritySettingsServiceRestTransport._BaseCreateSecuritySettings,
- SecuritySettingsServiceRestStub,
- ):
+ class _CreateSecuritySettings(SecuritySettingsServiceRestStub):
def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.CreateSecuritySettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateSecuritySettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -481,34 +479,49 @@ def __call__(
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseCreateSecuritySettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*}/securitySettings",
+ "body": "security_settings",
+ },
+ ]
request, metadata = self._interceptor.pre_create_security_settings(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseCreateSecuritySettings._get_transcoded_request(
- http_options, request
+ pb_request = gcdc_security_settings.CreateSecuritySettingsRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSecuritySettingsServiceRestTransport._BaseCreateSecuritySettings._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseCreateSecuritySettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SecuritySettingsServiceRestTransport._CreateSecuritySettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -524,34 +537,19 @@ def __call__(
resp = self._interceptor.post_create_security_settings(resp)
return resp
- class _DeleteSecuritySettings(
- _BaseSecuritySettingsServiceRestTransport._BaseDeleteSecuritySettings,
- SecuritySettingsServiceRestStub,
- ):
+ class _DeleteSecuritySettings(SecuritySettingsServiceRestStub):
def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.DeleteSecuritySettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteSecuritySettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -574,29 +572,40 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseDeleteSecuritySettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/securitySettings/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_security_settings(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseDeleteSecuritySettings._get_transcoded_request(
- http_options, request
- )
+ pb_request = security_settings.DeleteSecuritySettingsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseDeleteSecuritySettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SecuritySettingsServiceRestTransport._DeleteSecuritySettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -604,34 +613,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetSecuritySettings(
- _BaseSecuritySettingsServiceRestTransport._BaseGetSecuritySettings,
- SecuritySettingsServiceRestStub,
- ):
+ class _GetSecuritySettings(SecuritySettingsServiceRestStub):
def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.GetSecuritySettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetSecuritySettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -664,31 +658,40 @@ def __call__(
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseGetSecuritySettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/securitySettings/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_security_settings(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseGetSecuritySettings._get_transcoded_request(
- http_options, request
- )
+ pb_request = security_settings.GetSecuritySettingsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseGetSecuritySettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SecuritySettingsServiceRestTransport._GetSecuritySettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -704,34 +707,19 @@ def __call__(
resp = self._interceptor.post_get_security_settings(resp)
return resp
- class _ListSecuritySettings(
- _BaseSecuritySettingsServiceRestTransport._BaseListSecuritySettings,
- SecuritySettingsServiceRestStub,
- ):
+ class _ListSecuritySettings(SecuritySettingsServiceRestStub):
def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.ListSecuritySettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListSecuritySettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -760,29 +748,40 @@ def __call__(
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseListSecuritySettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*}/securitySettings",
+ },
+ ]
request, metadata = self._interceptor.pre_list_security_settings(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseListSecuritySettings._get_transcoded_request(
- http_options, request
- )
+ pb_request = security_settings.ListSecuritySettingsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseListSecuritySettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SecuritySettingsServiceRestTransport._ListSecuritySettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -798,35 +797,21 @@ def __call__(
resp = self._interceptor.post_list_security_settings(resp)
return resp
- class _UpdateSecuritySettings(
- _BaseSecuritySettingsServiceRestTransport._BaseUpdateSecuritySettings,
- SecuritySettingsServiceRestStub,
- ):
+ class _UpdateSecuritySettings(SecuritySettingsServiceRestStub):
def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.UpdateSecuritySettings")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateSecuritySettings")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "updateMask": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -859,34 +844,49 @@ def __call__(
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseUpdateSecuritySettings._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{security_settings.name=projects/*/locations/*/securitySettings/*}",
+ "body": "security_settings",
+ },
+ ]
request, metadata = self._interceptor.pre_update_security_settings(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseUpdateSecuritySettings._get_transcoded_request(
- http_options, request
+ pb_request = gcdc_security_settings.UpdateSecuritySettingsRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSecuritySettingsServiceRestTransport._BaseUpdateSecuritySettings._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseUpdateSecuritySettings._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SecuritySettingsServiceRestTransport._UpdateSecuritySettings._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -958,35 +958,7 @@ def update_security_settings(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseSecuritySettingsServiceRestTransport._BaseGetLocation,
- SecuritySettingsServiceRestStub,
- ):
- def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(SecuritySettingsServiceRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1010,27 +982,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SecuritySettingsServiceRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1038,9 +1015,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1048,35 +1024,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseSecuritySettingsServiceRestTransport._BaseListLocations,
- SecuritySettingsServiceRestStub,
- ):
- def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(SecuritySettingsServiceRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1100,29 +1048,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = (
- SecuritySettingsServiceRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1130,9 +1081,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1140,35 +1090,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseSecuritySettingsServiceRestTransport._BaseCancelOperation,
- SecuritySettingsServiceRestStub,
- ):
- def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(SecuritySettingsServiceRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1189,31 +1111,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = (
- SecuritySettingsServiceRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1227,35 +1156,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseSecuritySettingsServiceRestTransport._BaseGetOperation,
- SecuritySettingsServiceRestStub,
- ):
- def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(SecuritySettingsServiceRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1279,27 +1180,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SecuritySettingsServiceRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1307,9 +1217,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1317,35 +1226,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseSecuritySettingsServiceRestTransport._BaseListOperations,
- SecuritySettingsServiceRestStub,
- ):
- def __hash__(self):
- return hash("SecuritySettingsServiceRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(SecuritySettingsServiceRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1369,29 +1250,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseSecuritySettingsServiceRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseSecuritySettingsServiceRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSecuritySettingsServiceRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = (
- SecuritySettingsServiceRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1399,9 +1287,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py
index 2b40de95f602..31c0f794b2da 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -200,7 +201,10 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = SessionEntityTypesClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(SessionEntityTypesClient).get_transport_class,
+ type(SessionEntityTypesClient),
+ )
def __init__(
self,
@@ -393,8 +397,6 @@ async def sample_list_session_entity_types():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -958,7 +960,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1011,7 +1017,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1067,7 +1077,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1117,7 +1131,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1170,7 +1188,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py
index afdb8e5d6940..ee1d1813f98c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py
@@ -679,7 +679,7 @@ def __init__(
Type[SessionEntityTypesTransport],
Callable[..., SessionEntityTypesTransport],
] = (
- SessionEntityTypesClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., SessionEntityTypesTransport], transport)
)
@@ -816,8 +816,6 @@ def sample_list_session_entity_types():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1388,7 +1386,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1441,7 +1443,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1497,7 +1503,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1547,7 +1557,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1600,7 +1614,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py
index 4d6ad4359f75..e9c29b0c9e16 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import session_entity_type
@@ -65,8 +51,6 @@ def __init__(
request: session_entity_type.ListSessionEntityTypesRequest,
response: session_entity_type.ListSessionEntityTypesResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = session_entity_type.ListSessionEntityTypesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]:
@@ -141,8 +115,6 @@ def __init__(
request: session_entity_type.ListSessionEntityTypesRequest,
response: session_entity_type.ListSessionEntityTypesResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -154,17 +126,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = session_entity_type.ListSessionEntityTypesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -177,12 +144,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py
index d12b5bf149d2..9d47dcca4cae 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py
@@ -90,8 +90,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -104,7 +102,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -162,31 +160,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py
index fe8cb5e1f567..217a9ff9f467 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py
@@ -128,8 +128,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py
index 8a478b2d57ba..842ab2c0a72f 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -176,8 +175,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -234,9 +232,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -397,70 +392,36 @@ def delete_session_entity_type(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_session_entity_types: self._wrap_method(
+ self.list_session_entity_types: gapic_v1.method_async.wrap_method(
self.list_session_entity_types,
default_timeout=None,
client_info=client_info,
),
- self.get_session_entity_type: self._wrap_method(
+ self.get_session_entity_type: gapic_v1.method_async.wrap_method(
self.get_session_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.create_session_entity_type: self._wrap_method(
+ self.create_session_entity_type: gapic_v1.method_async.wrap_method(
self.create_session_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.update_session_entity_type: self._wrap_method(
+ self.update_session_entity_type: gapic_v1.method_async.wrap_method(
self.update_session_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.delete_session_entity_type: self._wrap_method(
+ self.delete_session_entity_type: gapic_v1.method_async.wrap_method(
self.delete_session_entity_type,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/rest.py
index ebed5b210724..a9335a0f505d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/rest.py
@@ -16,33 +16,37 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+
+
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
from google.cloud.dialogflowcx_v3beta1.types import (
session_entity_type as gcdc_session_entity_type,
)
from google.cloud.dialogflowcx_v3beta1.types import session_entity_type
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseSessionEntityTypesRestTransport
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
-
+from .base import SessionEntityTypesTransport
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
@@ -345,8 +349,8 @@ class SessionEntityTypesRestStub:
_interceptor: SessionEntityTypesRestInterceptor
-class SessionEntityTypesRestTransport(_BaseSessionEntityTypesRestTransport):
- """REST backend synchronous transport for SessionEntityTypes.
+class SessionEntityTypesRestTransport(SessionEntityTypesTransport):
+ """REST backend transport for SessionEntityTypes.
Service for managing
[SessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityType].
@@ -356,6 +360,7 @@ class SessionEntityTypesRestTransport(_BaseSessionEntityTypesRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -409,12 +414,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -425,35 +439,19 @@ def __init__(
self._interceptor = interceptor or SessionEntityTypesRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateSessionEntityType(
- _BaseSessionEntityTypesRestTransport._BaseCreateSessionEntityType,
- SessionEntityTypesRestStub,
- ):
+ class _CreateSessionEntityType(SessionEntityTypesRestStub):
def __hash__(self):
- return hash("SessionEntityTypesRestTransport.CreateSessionEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateSessionEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -498,36 +496,54 @@ def __call__(
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseCreateSessionEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/sessions/*}/entityTypes",
+ "body": "session_entity_type",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*/sessions/*}/entityTypes",
+ "body": "session_entity_type",
+ },
+ ]
request, metadata = self._interceptor.pre_create_session_entity_type(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseCreateSessionEntityType._get_transcoded_request(
- http_options, request
+ pb_request = gcdc_session_entity_type.CreateSessionEntityTypeRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSessionEntityTypesRestTransport._BaseCreateSessionEntityType._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseCreateSessionEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SessionEntityTypesRestTransport._CreateSessionEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -543,34 +559,19 @@ def __call__(
resp = self._interceptor.post_create_session_entity_type(resp)
return resp
- class _DeleteSessionEntityType(
- _BaseSessionEntityTypesRestTransport._BaseDeleteSessionEntityType,
- SessionEntityTypesRestStub,
- ):
+ class _DeleteSessionEntityType(SessionEntityTypesRestStub):
def __hash__(self):
- return hash("SessionEntityTypesRestTransport.DeleteSessionEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteSessionEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -594,31 +595,44 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseDeleteSessionEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/sessions/*/entityTypes/*}",
+ },
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/sessions/*/entityTypes/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_session_entity_type(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseDeleteSessionEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = session_entity_type.DeleteSessionEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseDeleteSessionEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SessionEntityTypesRestTransport._DeleteSessionEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -626,34 +640,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetSessionEntityType(
- _BaseSessionEntityTypesRestTransport._BaseGetSessionEntityType,
- SessionEntityTypesRestStub,
- ):
+ class _GetSessionEntityType(SessionEntityTypesRestStub):
def __hash__(self):
- return hash("SessionEntityTypesRestTransport.GetSessionEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetSessionEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -697,31 +696,44 @@ def __call__(
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseGetSessionEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/sessions/*/entityTypes/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/sessions/*/entityTypes/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_session_entity_type(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseGetSessionEntityType._get_transcoded_request(
- http_options, request
- )
+ pb_request = session_entity_type.GetSessionEntityTypeRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseGetSessionEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SessionEntityTypesRestTransport._GetSessionEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -737,34 +749,19 @@ def __call__(
resp = self._interceptor.post_get_session_entity_type(resp)
return resp
- class _ListSessionEntityTypes(
- _BaseSessionEntityTypesRestTransport._BaseListSessionEntityTypes,
- SessionEntityTypesRestStub,
- ):
+ class _ListSessionEntityTypes(SessionEntityTypesRestStub):
def __hash__(self):
- return hash("SessionEntityTypesRestTransport.ListSessionEntityTypes")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListSessionEntityTypes")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -793,31 +790,44 @@ def __call__(
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseListSessionEntityTypes._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/sessions/*}/entityTypes",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*/sessions/*}/entityTypes",
+ },
+ ]
request, metadata = self._interceptor.pre_list_session_entity_types(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseListSessionEntityTypes._get_transcoded_request(
- http_options, request
- )
+ pb_request = session_entity_type.ListSessionEntityTypesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseListSessionEntityTypes._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SessionEntityTypesRestTransport._ListSessionEntityTypes._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -833,35 +843,19 @@ def __call__(
resp = self._interceptor.post_list_session_entity_types(resp)
return resp
- class _UpdateSessionEntityType(
- _BaseSessionEntityTypesRestTransport._BaseUpdateSessionEntityType,
- SessionEntityTypesRestStub,
- ):
+ class _UpdateSessionEntityType(SessionEntityTypesRestStub):
def __hash__(self):
- return hash("SessionEntityTypesRestTransport.UpdateSessionEntityType")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateSessionEntityType")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -906,36 +900,54 @@ def __call__(
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseUpdateSessionEntityType._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{session_entity_type.name=projects/*/locations/*/agents/*/sessions/*/entityTypes/*}",
+ "body": "session_entity_type",
+ },
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{session_entity_type.name=projects/*/locations/*/agents/*/environments/*/sessions/*/entityTypes/*}",
+ "body": "session_entity_type",
+ },
+ ]
request, metadata = self._interceptor.pre_update_session_entity_type(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseUpdateSessionEntityType._get_transcoded_request(
- http_options, request
+ pb_request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSessionEntityTypesRestTransport._BaseUpdateSessionEntityType._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseUpdateSessionEntityType._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = (
- SessionEntityTypesRestTransport._UpdateSessionEntityType._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1009,35 +1021,7 @@ def update_session_entity_type(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseSessionEntityTypesRestTransport._BaseGetLocation,
- SessionEntityTypesRestStub,
- ):
- def __hash__(self):
- return hash("SessionEntityTypesRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(SessionEntityTypesRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1061,27 +1045,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionEntityTypesRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1089,9 +1078,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1099,35 +1087,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseSessionEntityTypesRestTransport._BaseListLocations,
- SessionEntityTypesRestStub,
- ):
- def __hash__(self):
- return hash("SessionEntityTypesRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(SessionEntityTypesRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1151,27 +1111,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionEntityTypesRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1179,9 +1144,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1189,35 +1153,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseSessionEntityTypesRestTransport._BaseCancelOperation,
- SessionEntityTypesRestStub,
- ):
- def __hash__(self):
- return hash("SessionEntityTypesRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(SessionEntityTypesRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1238,29 +1174,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionEntityTypesRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1274,35 +1219,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseSessionEntityTypesRestTransport._BaseGetOperation,
- SessionEntityTypesRestStub,
- ):
- def __hash__(self):
- return hash("SessionEntityTypesRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(SessionEntityTypesRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1326,27 +1243,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionEntityTypesRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1354,9 +1280,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1364,35 +1289,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseSessionEntityTypesRestTransport._BaseListOperations,
- SessionEntityTypesRestStub,
- ):
- def __hash__(self):
- return hash("SessionEntityTypesRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(SessionEntityTypesRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1416,27 +1313,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseSessionEntityTypesRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseSessionEntityTypesRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionEntityTypesRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionEntityTypesRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1444,9 +1350,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py
index ad29431b6ba5..8fd3f1e71fcd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
AsyncIterable,
@@ -217,7 +218,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = SessionsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(SessionsClient).get_transport_class, type(SessionsClient)
+ )
def __init__(
self,
@@ -931,7 +934,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -984,7 +991,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1040,7 +1051,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1090,7 +1105,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1143,7 +1162,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py
index 723e0d9092ac..ccc11392f262 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py
@@ -961,7 +961,7 @@ def __init__(
transport_init: Union[
Type[SessionsTransport], Callable[..., SessionsTransport]
] = (
- SessionsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., SessionsTransport], transport)
)
@@ -1627,7 +1627,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1680,7 +1684,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1736,7 +1744,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1786,7 +1798,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1839,7 +1855,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py
index 7e1042541ff1..fc6418650b65 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py
@@ -86,8 +86,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -100,7 +98,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -172,31 +170,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py
index 30ec6748269d..64bf45cf575e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py
index bd442bfa5f78..79991dbfe377 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -445,7 +440,7 @@ def submit_answer_feedback(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.detect_intent: self._wrap_method(
+ self.detect_intent: gapic_v1.method_async.wrap_method(
self.detect_intent,
default_retry=retries.AsyncRetry(
initial=0.1,
@@ -459,70 +454,36 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=220.0,
client_info=client_info,
),
- self.server_streaming_detect_intent: self._wrap_method(
+ self.server_streaming_detect_intent: gapic_v1.method_async.wrap_method(
self.server_streaming_detect_intent,
default_timeout=220.0,
client_info=client_info,
),
- self.streaming_detect_intent: self._wrap_method(
+ self.streaming_detect_intent: gapic_v1.method_async.wrap_method(
self.streaming_detect_intent,
default_timeout=220.0,
client_info=client_info,
),
- self.match_intent: self._wrap_method(
+ self.match_intent: gapic_v1.method_async.wrap_method(
self.match_intent,
default_timeout=None,
client_info=client_info,
),
- self.fulfill_intent: self._wrap_method(
+ self.fulfill_intent: gapic_v1.method_async.wrap_method(
self.fulfill_intent,
default_timeout=None,
client_info=client_info,
),
- self.submit_answer_feedback: self._wrap_method(
+ self.submit_answer_feedback: gapic_v1.method_async.wrap_method(
self.submit_answer_feedback,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/rest.py
index bd48edb919ab..875a729e3303 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/rest.py
@@ -16,30 +16,34 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import session
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseSessionsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import session
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import SessionsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -336,8 +340,8 @@ class SessionsRestStub:
_interceptor: SessionsRestInterceptor
-class SessionsRestTransport(_BaseSessionsRestTransport):
- """REST backend synchronous transport for Sessions.
+class SessionsRestTransport(SessionsTransport):
+ """REST backend transport for Sessions.
A session represents an interaction with a user. You retrieve user
input and pass it to the
@@ -349,6 +353,7 @@ class SessionsRestTransport(_BaseSessionsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -402,12 +407,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -418,32 +432,19 @@ def __init__(
self._interceptor = interceptor or SessionsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _DetectIntent(_BaseSessionsRestTransport._BaseDetectIntent, SessionsRestStub):
+ class _DetectIntent(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.DetectIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("DetectIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -471,36 +472,50 @@ def __call__(
"""
- http_options = (
- _BaseSessionsRestTransport._BaseDetectIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/sessions/*}:detectIntent",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/environments/*/sessions/*}:detectIntent",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_detect_intent(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseDetectIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = session.DetectIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSessionsRestTransport._BaseDetectIntent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseDetectIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SessionsRestTransport._DetectIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -516,34 +531,9 @@ def __call__(
resp = self._interceptor.post_detect_intent(resp)
return resp
- class _FulfillIntent(
- _BaseSessionsRestTransport._BaseFulfillIntent, SessionsRestStub
- ):
+ class _FulfillIntent(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.FulfillIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("FulfillIntent")
def __call__(
self,
@@ -569,36 +559,49 @@ def __call__(
Response of [FulfillIntent][]
"""
- http_options = (
- _BaseSessionsRestTransport._BaseFulfillIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{match_intent_request.session=projects/*/locations/*/agents/*/sessions/*}:fulfillIntent",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{match_intent_request.session=projects/*/locations/*/agents/*/environments/*/sessions/*}:fulfillIntent",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_fulfill_intent(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseFulfillIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = session.FulfillIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSessionsRestTransport._BaseFulfillIntent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseFulfillIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params["$alt"] = "json;enum-encoding=int"
+
# Send the request
- response = SessionsRestTransport._FulfillIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -614,32 +617,19 @@ def __call__(
resp = self._interceptor.post_fulfill_intent(resp)
return resp
- class _MatchIntent(_BaseSessionsRestTransport._BaseMatchIntent, SessionsRestStub):
+ class _MatchIntent(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.MatchIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("MatchIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -665,36 +655,50 @@ def __call__(
Response of [MatchIntent][].
"""
- http_options = (
- _BaseSessionsRestTransport._BaseMatchIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/sessions/*}:matchIntent",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/environments/*/sessions/*}:matchIntent",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_match_intent(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseMatchIntent._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = session.MatchIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseSessionsRestTransport._BaseMatchIntent._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseMatchIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SessionsRestTransport._MatchIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -710,35 +714,19 @@ def __call__(
resp = self._interceptor.post_match_intent(resp)
return resp
- class _ServerStreamingDetectIntent(
- _BaseSessionsRestTransport._BaseServerStreamingDetectIntent, SessionsRestStub
- ):
+ class _ServerStreamingDetectIntent(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.ServerStreamingDetectIntent")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- stream=True,
- )
- return response
+ return hash("ServerStreamingDetectIntent")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -767,34 +755,52 @@ def __call__(
"""
- http_options = (
- _BaseSessionsRestTransport._BaseServerStreamingDetectIntent._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/sessions/*}:serverStreamingDetectIntent",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/environments/*/sessions/*}:serverStreamingDetectIntent",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_server_streaming_detect_intent(
request, metadata
)
- transcoded_request = _BaseSessionsRestTransport._BaseServerStreamingDetectIntent._get_transcoded_request(
- http_options, request
- )
+ pb_request = session.DetectIntentRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseSessionsRestTransport._BaseServerStreamingDetectIntent._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionsRestTransport._BaseServerStreamingDetectIntent._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SessionsRestTransport._ServerStreamingDetectIntent._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -809,11 +815,9 @@ def __call__(
resp = self._interceptor.post_server_streaming_detect_intent(resp)
return resp
- class _StreamingDetectIntent(
- _BaseSessionsRestTransport._BaseStreamingDetectIntent, SessionsRestStub
- ):
+ class _StreamingDetectIntent(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.StreamingDetectIntent")
+ return hash("StreamingDetectIntent")
def __call__(
self,
@@ -827,34 +831,19 @@ def __call__(
"Method StreamingDetectIntent is not available over REST transport"
)
- class _SubmitAnswerFeedback(
- _BaseSessionsRestTransport._BaseSubmitAnswerFeedback, SessionsRestStub
- ):
+ class _SubmitAnswerFeedback(SessionsRestStub):
def __hash__(self):
- return hash("SessionsRestTransport.SubmitAnswerFeedback")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("SubmitAnswerFeedback")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -883,34 +872,47 @@ def __call__(
"""
- http_options = (
- _BaseSessionsRestTransport._BaseSubmitAnswerFeedback._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{session=projects/*/locations/*/agents/*/sessions/*}:submitAnswerFeedback",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_submit_answer_feedback(
request, metadata
)
- transcoded_request = _BaseSessionsRestTransport._BaseSubmitAnswerFeedback._get_transcoded_request(
- http_options, request
- )
+ pb_request = session.SubmitAnswerFeedbackRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseSessionsRestTransport._BaseSubmitAnswerFeedback._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseSessionsRestTransport._BaseSubmitAnswerFeedback._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = SessionsRestTransport._SubmitAnswerFeedback._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -980,32 +982,7 @@ def submit_answer_feedback(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseSessionsRestTransport._BaseGetLocation, SessionsRestStub):
- def __hash__(self):
- return hash("SessionsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(SessionsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1029,31 +1006,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseSessionsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1061,9 +1039,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1071,34 +1048,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseSessionsRestTransport._BaseListLocations, SessionsRestStub
- ):
- def __hash__(self):
- return hash("SessionsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(SessionsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1122,31 +1072,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseSessionsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1154,9 +1105,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1164,34 +1114,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseSessionsRestTransport._BaseCancelOperation, SessionsRestStub
- ):
- def __hash__(self):
- return hash("SessionsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(SessionsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1212,33 +1135,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseSessionsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1252,32 +1180,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseSessionsRestTransport._BaseGetOperation, SessionsRestStub):
- def __hash__(self):
- return hash("SessionsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(SessionsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1301,31 +1204,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseSessionsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1333,9 +1241,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1343,34 +1250,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseSessionsRestTransport._BaseListOperations, SessionsRestStub
- ):
- def __hash__(self):
- return hash("SessionsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(SessionsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1394,31 +1274,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseSessionsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseSessionsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseSessionsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = SessionsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1426,9 +1311,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py
index 5dda144a62ff..9456425bc212 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -85,8 +86,6 @@ class TestCasesAsyncClient:
parse_intent_path = staticmethod(TestCasesClient.parse_intent_path)
page_path = staticmethod(TestCasesClient.page_path)
parse_page_path = staticmethod(TestCasesClient.parse_page_path)
- playbook_path = staticmethod(TestCasesClient.playbook_path)
- parse_playbook_path = staticmethod(TestCasesClient.parse_playbook_path)
test_case_path = staticmethod(TestCasesClient.test_case_path)
parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path)
test_case_result_path = staticmethod(TestCasesClient.test_case_result_path)
@@ -219,7 +218,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = TestCasesClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(TestCasesClient).get_transport_class, type(TestCasesClient)
+ )
def __init__(
self,
@@ -400,8 +401,6 @@ async def sample_list_test_cases():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1486,8 +1485,6 @@ async def sample_list_test_case_results():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1631,7 +1628,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1684,7 +1685,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1740,7 +1745,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1790,7 +1799,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1843,7 +1856,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py
index ae68104a2149..aff021d9cf6d 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py
@@ -336,30 +336,6 @@ def parse_page_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
- @staticmethod
- def playbook_path(
- project: str,
- location: str,
- agent: str,
- playbook: str,
- ) -> str:
- """Returns a fully-qualified playbook string."""
- return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
- project=project,
- location=location,
- agent=agent,
- playbook=playbook,
- )
-
- @staticmethod
- def parse_playbook_path(path: str) -> Dict[str, str]:
- """Parses a playbook path into its component segments."""
- m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$",
- path,
- )
- return m.groupdict() if m else {}
-
@staticmethod
def test_case_path(
project: str,
@@ -936,7 +912,7 @@ def __init__(
transport_init: Union[
Type[TestCasesTransport], Callable[..., TestCasesTransport]
] = (
- TestCasesClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., TestCasesTransport], transport)
)
@@ -1063,8 +1039,6 @@ def sample_list_test_cases():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -2124,8 +2098,6 @@ def sample_list_test_case_results():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -2279,7 +2251,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2332,7 +2308,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2388,7 +2368,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2438,7 +2422,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -2491,7 +2479,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py
index fa6e9162fc31..5f9f4e2f7bb5 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import test_case
@@ -65,8 +51,6 @@ def __init__(
request: test_case.ListTestCasesRequest,
response: test_case.ListTestCasesResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = test_case.ListTestCasesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[test_case.ListTestCasesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[test_case.TestCase]:
@@ -139,8 +113,6 @@ def __init__(
request: test_case.ListTestCasesRequest,
response: test_case.ListTestCasesResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = test_case.ListTestCasesRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[test_case.ListTestCasesResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[test_case.TestCase]:
@@ -217,8 +179,6 @@ def __init__(
request: test_case.ListTestCaseResultsRequest,
response: test_case.ListTestCaseResultsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -230,17 +190,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = test_case.ListTestCaseResultsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -251,12 +206,7 @@ def pages(self) -> Iterator[test_case.ListTestCaseResultsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[test_case.TestCaseResult]:
@@ -291,8 +241,6 @@ def __init__(
request: test_case.ListTestCaseResultsRequest,
response: test_case.ListTestCaseResultsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -304,17 +252,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = test_case.ListTestCaseResultsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -325,12 +268,7 @@ async def pages(self) -> AsyncIterator[test_case.ListTestCaseResultsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[test_case.TestCaseResult]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py
index 460a775642d4..dedfbe14c975 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -195,31 +193,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py
index c02e192d31a6..27550a68bb83 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py
@@ -128,8 +128,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py
index 178eb2726916..7511b7eef6d0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -176,8 +175,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -234,9 +232,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -647,105 +642,71 @@ def get_test_case_result(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_test_cases: self._wrap_method(
+ self.list_test_cases: gapic_v1.method_async.wrap_method(
self.list_test_cases,
default_timeout=None,
client_info=client_info,
),
- self.batch_delete_test_cases: self._wrap_method(
+ self.batch_delete_test_cases: gapic_v1.method_async.wrap_method(
self.batch_delete_test_cases,
default_timeout=None,
client_info=client_info,
),
- self.get_test_case: self._wrap_method(
+ self.get_test_case: gapic_v1.method_async.wrap_method(
self.get_test_case,
default_timeout=None,
client_info=client_info,
),
- self.create_test_case: self._wrap_method(
+ self.create_test_case: gapic_v1.method_async.wrap_method(
self.create_test_case,
default_timeout=None,
client_info=client_info,
),
- self.update_test_case: self._wrap_method(
+ self.update_test_case: gapic_v1.method_async.wrap_method(
self.update_test_case,
default_timeout=None,
client_info=client_info,
),
- self.run_test_case: self._wrap_method(
+ self.run_test_case: gapic_v1.method_async.wrap_method(
self.run_test_case,
default_timeout=None,
client_info=client_info,
),
- self.batch_run_test_cases: self._wrap_method(
+ self.batch_run_test_cases: gapic_v1.method_async.wrap_method(
self.batch_run_test_cases,
default_timeout=None,
client_info=client_info,
),
- self.calculate_coverage: self._wrap_method(
+ self.calculate_coverage: gapic_v1.method_async.wrap_method(
self.calculate_coverage,
default_timeout=None,
client_info=client_info,
),
- self.import_test_cases: self._wrap_method(
+ self.import_test_cases: gapic_v1.method_async.wrap_method(
self.import_test_cases,
default_timeout=None,
client_info=client_info,
),
- self.export_test_cases: self._wrap_method(
+ self.export_test_cases: gapic_v1.method_async.wrap_method(
self.export_test_cases,
default_timeout=None,
client_info=client_info,
),
- self.list_test_case_results: self._wrap_method(
+ self.list_test_case_results: gapic_v1.method_async.wrap_method(
self.list_test_case_results,
default_timeout=None,
client_info=client_info,
),
- self.get_test_case_result: self._wrap_method(
+ self.get_test_case_result: gapic_v1.method_async.wrap_method(
self.get_test_case_result,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/rest.py
index 07452520d774..09b2a57745d0 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import test_case
-from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseTestCasesRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import test_case
+from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import TestCasesTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -542,8 +552,8 @@ class TestCasesRestStub:
_interceptor: TestCasesRestInterceptor
-class TestCasesRestTransport(_BaseTestCasesRestTransport):
- """REST backend synchronous transport for TestCases.
+class TestCasesRestTransport(TestCasesTransport):
+ """REST backend transport for TestCases.
Service for managing [Test
Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case
@@ -554,6 +564,7 @@ class TestCasesRestTransport(_BaseTestCasesRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -607,12 +618,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -682,34 +702,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _BatchDeleteTestCases(
- _BaseTestCasesRestTransport._BaseBatchDeleteTestCases, TestCasesRestStub
- ):
+ class _BatchDeleteTestCases(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.BatchDeleteTestCases")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("BatchDeleteTestCases")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -732,34 +737,47 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseBatchDeleteTestCases._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases:batchDelete",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_batch_delete_test_cases(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseBatchDeleteTestCases._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.BatchDeleteTestCasesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseTestCasesRestTransport._BaseBatchDeleteTestCases._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTestCasesRestTransport._BaseBatchDeleteTestCases._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._BatchDeleteTestCases._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -767,34 +785,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _BatchRunTestCases(
- _BaseTestCasesRestTransport._BaseBatchRunTestCases, TestCasesRestStub
- ):
+ class _BatchRunTestCases(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.BatchRunTestCases")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("BatchRunTestCases")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -824,34 +827,47 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseBatchRunTestCases._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases:batchRun",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_batch_run_test_cases(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseBatchRunTestCases._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.BatchRunTestCasesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseTestCasesRestTransport._BaseBatchRunTestCases._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTestCasesRestTransport._BaseBatchRunTestCases._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._BatchRunTestCases._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -865,33 +881,21 @@ def __call__(
resp = self._interceptor.post_batch_run_test_cases(resp)
return resp
- class _CalculateCoverage(
- _BaseTestCasesRestTransport._BaseCalculateCoverage, TestCasesRestStub
- ):
+ class _CalculateCoverage(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.CalculateCoverage")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("CalculateCoverage")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "type": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -920,29 +924,40 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseCalculateCoverage._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{agent=projects/*/locations/*/agents/*}/testCases:calculateCoverage",
+ },
+ ]
request, metadata = self._interceptor.pre_calculate_coverage(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseCalculateCoverage._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.CalculateCoverageRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTestCasesRestTransport._BaseCalculateCoverage._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._CalculateCoverage._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -958,34 +973,19 @@ def __call__(
resp = self._interceptor.post_calculate_coverage(resp)
return resp
- class _CreateTestCase(
- _BaseTestCasesRestTransport._BaseCreateTestCase, TestCasesRestStub
- ):
+ class _CreateTestCase(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.CreateTestCase")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateTestCase")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1012,40 +1012,47 @@ def __call__(
Represents a test case.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseCreateTestCase._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases",
+ "body": "test_case",
+ },
+ ]
request, metadata = self._interceptor.pre_create_test_case(
request, metadata
)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseCreateTestCase._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_test_case.CreateTestCaseRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseTestCasesRestTransport._BaseCreateTestCase._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseCreateTestCase._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._CreateTestCase._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1061,34 +1068,19 @@ def __call__(
resp = self._interceptor.post_create_test_case(resp)
return resp
- class _ExportTestCases(
- _BaseTestCasesRestTransport._BaseExportTestCases, TestCasesRestStub
- ):
+ class _ExportTestCases(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.ExportTestCases")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportTestCases")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1118,38 +1110,47 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseExportTestCases._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_test_cases(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseExportTestCases._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.ExportTestCasesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseTestCasesRestTransport._BaseExportTestCases._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseExportTestCases._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._ExportTestCases._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1163,31 +1164,19 @@ def __call__(
resp = self._interceptor.post_export_test_cases(resp)
return resp
- class _GetTestCase(_BaseTestCasesRestTransport._BaseGetTestCase, TestCasesRestStub):
+ class _GetTestCase(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.GetTestCase")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetTestCase")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1214,31 +1203,38 @@ def __call__(
Represents a test case.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseGetTestCase._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/testCases/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_test_case(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseGetTestCase._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = test_case.GetTestCaseRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseGetTestCase._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._GetTestCase._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1254,33 +1250,19 @@ def __call__(
resp = self._interceptor.post_get_test_case(resp)
return resp
- class _GetTestCaseResult(
- _BaseTestCasesRestTransport._BaseGetTestCaseResult, TestCasesRestStub
- ):
+ class _GetTestCaseResult(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.GetTestCaseResult")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetTestCaseResult")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1309,29 +1291,40 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseGetTestCaseResult._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/testCases/*/results/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_test_case_result(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseGetTestCaseResult._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.GetTestCaseResultRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTestCasesRestTransport._BaseGetTestCaseResult._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._GetTestCaseResult._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1347,34 +1340,19 @@ def __call__(
resp = self._interceptor.post_get_test_case_result(resp)
return resp
- class _ImportTestCases(
- _BaseTestCasesRestTransport._BaseImportTestCases, TestCasesRestStub
- ):
+ class _ImportTestCases(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.ImportTestCases")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ImportTestCases")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1404,38 +1382,47 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseImportTestCases._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases:import",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_import_test_cases(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseImportTestCases._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.ImportTestCasesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseTestCasesRestTransport._BaseImportTestCases._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseImportTestCases._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._ImportTestCases._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1449,33 +1436,19 @@ def __call__(
resp = self._interceptor.post_import_test_cases(resp)
return resp
- class _ListTestCaseResults(
- _BaseTestCasesRestTransport._BaseListTestCaseResults, TestCasesRestStub
- ):
+ class _ListTestCaseResults(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.ListTestCaseResults")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListTestCaseResults")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1504,29 +1477,40 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseListTestCaseResults._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/testCases/*}/results",
+ },
+ ]
request, metadata = self._interceptor.pre_list_test_case_results(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseListTestCaseResults._get_transcoded_request(
- http_options, request
- )
+ pb_request = test_case.ListTestCaseResultsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTestCasesRestTransport._BaseListTestCaseResults._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._ListTestCaseResults._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1542,33 +1526,19 @@ def __call__(
resp = self._interceptor.post_list_test_case_results(resp)
return resp
- class _ListTestCases(
- _BaseTestCasesRestTransport._BaseListTestCases, TestCasesRestStub
- ):
+ class _ListTestCases(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.ListTestCases")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListTestCases")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1597,31 +1567,38 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseListTestCases._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases",
+ },
+ ]
request, metadata = self._interceptor.pre_list_test_cases(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseListTestCases._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = test_case.ListTestCasesRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseListTestCases._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._ListTestCases._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1637,32 +1614,19 @@ def __call__(
resp = self._interceptor.post_list_test_cases(resp)
return resp
- class _RunTestCase(_BaseTestCasesRestTransport._BaseRunTestCase, TestCasesRestStub):
+ class _RunTestCase(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.RunTestCase")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("RunTestCase")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1692,36 +1656,45 @@ def __call__(
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseRunTestCase._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/testCases/*}:run",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_run_test_case(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseRunTestCase._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = test_case.RunTestCaseRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseTestCasesRestTransport._BaseRunTestCase._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseRunTestCase._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._RunTestCase._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1735,34 +1708,21 @@ def __call__(
resp = self._interceptor.post_run_test_case(resp)
return resp
- class _UpdateTestCase(
- _BaseTestCasesRestTransport._BaseUpdateTestCase, TestCasesRestStub
- ):
+ class _UpdateTestCase(TestCasesRestStub):
def __hash__(self):
- return hash("TestCasesRestTransport.UpdateTestCase")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateTestCase")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "updateMask": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1789,40 +1749,47 @@ def __call__(
Represents a test case.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseUpdateTestCase._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{test_case.name=projects/*/locations/*/agents/*/testCases/*}",
+ "body": "test_case",
+ },
+ ]
request, metadata = self._interceptor.pre_update_test_case(
request, metadata
)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseUpdateTestCase._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_test_case.UpdateTestCaseRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseTestCasesRestTransport._BaseUpdateTestCase._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseUpdateTestCase._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TestCasesRestTransport._UpdateTestCase._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1942,32 +1909,7 @@ def update_test_case(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseTestCasesRestTransport._BaseGetLocation, TestCasesRestStub):
- def __hash__(self):
- return hash("TestCasesRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(TestCasesRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1991,31 +1933,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TestCasesRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2023,9 +1966,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -2033,34 +1975,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseTestCasesRestTransport._BaseListLocations, TestCasesRestStub
- ):
- def __hash__(self):
- return hash("TestCasesRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(TestCasesRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -2084,31 +1999,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TestCasesRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2116,9 +2032,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -2126,34 +2041,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseTestCasesRestTransport._BaseCancelOperation, TestCasesRestStub
- ):
- def __hash__(self):
- return hash("TestCasesRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(TestCasesRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -2174,31 +2062,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseTestCasesRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TestCasesRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2212,34 +2107,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseTestCasesRestTransport._BaseGetOperation, TestCasesRestStub
- ):
- def __hash__(self):
- return hash("TestCasesRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(TestCasesRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -2263,31 +2131,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TestCasesRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2295,9 +2168,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -2305,34 +2177,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseTestCasesRestTransport._BaseListOperations, TestCasesRestStub
- ):
- def __hash__(self):
- return hash("TestCasesRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(TestCasesRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -2356,31 +2201,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseTestCasesRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseTestCasesRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseTestCasesRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TestCasesRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -2388,9 +2238,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/async_client.py
index 7949793207a5..48dc2f4a7bc1 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -71,8 +72,6 @@ class ToolsAsyncClient:
_DEFAULT_ENDPOINT_TEMPLATE = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE
_DEFAULT_UNIVERSE = ToolsClient._DEFAULT_UNIVERSE
- service_path = staticmethod(ToolsClient.service_path)
- parse_service_path = staticmethod(ToolsClient.parse_service_path)
tool_path = staticmethod(ToolsClient.tool_path)
parse_tool_path = staticmethod(ToolsClient.parse_tool_path)
common_billing_account_path = staticmethod(ToolsClient.common_billing_account_path)
@@ -187,7 +186,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = ToolsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(ToolsClient).get_transport_class, type(ToolsClient)
+ )
def __init__(
self,
@@ -495,8 +496,6 @@ async def sample_list_tools():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -965,7 +964,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1018,7 +1021,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1074,7 +1081,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1124,7 +1135,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1177,7 +1192,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/client.py
index 6c0f0b15296d..544dab9541cf 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/client.py
@@ -190,30 +190,6 @@ def transport(self) -> ToolsTransport:
"""
return self._transport
- @staticmethod
- def service_path(
- project: str,
- location: str,
- namespace: str,
- service: str,
- ) -> str:
- """Returns a fully-qualified service string."""
- return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(
- project=project,
- location=location,
- namespace=namespace,
- service=service,
- )
-
- @staticmethod
- def parse_service_path(path: str) -> Dict[str, str]:
- """Parses a service path into its component segments."""
- m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$",
- path,
- )
- return m.groupdict() if m else {}
-
@staticmethod
def tool_path(
project: str,
@@ -690,7 +666,7 @@ def __init__(
transport_init: Union[
Type[ToolsTransport], Callable[..., ToolsTransport]
] = (
- ToolsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., ToolsTransport], transport)
)
@@ -941,8 +917,6 @@ def sample_list_tools():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1415,7 +1389,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1468,7 +1446,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1524,7 +1506,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1574,7 +1560,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1627,7 +1617,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/pagers.py
index e1e0fc8c43d1..2afcc022330a 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import tool
@@ -65,8 +51,6 @@ def __init__(
request: tool.ListToolsRequest,
response: tool.ListToolsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListToolsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = tool.ListToolsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[tool.ListToolsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[tool.Tool]:
@@ -139,8 +113,6 @@ def __init__(
request: tool.ListToolsRequest,
response: tool.ListToolsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListToolsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = tool.ListToolsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[tool.ListToolsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[tool.Tool]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/base.py
index 39733c9b4fc5..6e5564245208 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -165,31 +163,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc.py
index 34f62aebc7e2..a2fea8c72de5 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc_asyncio.py
index ae470340c779..4fdd8afb3e69 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -427,75 +422,41 @@ def delete_tool(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.create_tool: self._wrap_method(
+ self.create_tool: gapic_v1.method_async.wrap_method(
self.create_tool,
default_timeout=None,
client_info=client_info,
),
- self.list_tools: self._wrap_method(
+ self.list_tools: gapic_v1.method_async.wrap_method(
self.list_tools,
default_timeout=None,
client_info=client_info,
),
- self.export_tools: self._wrap_method(
+ self.export_tools: gapic_v1.method_async.wrap_method(
self.export_tools,
default_timeout=None,
client_info=client_info,
),
- self.get_tool: self._wrap_method(
+ self.get_tool: gapic_v1.method_async.wrap_method(
self.get_tool,
default_timeout=None,
client_info=client_info,
),
- self.update_tool: self._wrap_method(
+ self.update_tool: gapic_v1.method_async.wrap_method(
self.update_tool,
default_timeout=None,
client_info=client_info,
),
- self.delete_tool: self._wrap_method(
+ self.delete_tool: gapic_v1.method_async.wrap_method(
self.delete_tool,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/rest.py
index d171dc086427..607c71037850 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/tools/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import tool
-from google.cloud.dialogflowcx_v3beta1.types import tool as gcdc_tool
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseToolsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import tool
+from google.cloud.dialogflowcx_v3beta1.types import tool as gcdc_tool
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import ToolsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -344,8 +354,8 @@ class ToolsRestStub:
_interceptor: ToolsRestInterceptor
-class ToolsRestTransport(_BaseToolsRestTransport):
- """REST backend synchronous transport for Tools.
+class ToolsRestTransport(ToolsTransport):
+ """REST backend transport for Tools.
Service for managing
[Tools][google.cloud.dialogflow.cx.v3beta1.Tool].
@@ -355,6 +365,7 @@ class ToolsRestTransport(_BaseToolsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -408,12 +419,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -483,32 +503,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CreateTool(_BaseToolsRestTransport._BaseCreateTool, ToolsRestStub):
+ class _CreateTool(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.CreateTool")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateTool")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -541,34 +548,45 @@ def __call__(
"""
- http_options = _BaseToolsRestTransport._BaseCreateTool._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/tools",
+ "body": "tool",
+ },
+ ]
request, metadata = self._interceptor.pre_create_tool(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseCreateTool._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_tool.CreateToolRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseToolsRestTransport._BaseCreateTool._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseCreateTool._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._CreateTool._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -584,31 +602,19 @@ def __call__(
resp = self._interceptor.post_create_tool(resp)
return resp
- class _DeleteTool(_BaseToolsRestTransport._BaseDeleteTool, ToolsRestStub):
+ class _DeleteTool(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.DeleteTool")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteTool")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -631,29 +637,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = _BaseToolsRestTransport._BaseDeleteTool._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_tool(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseDeleteTool._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = tool.DeleteToolRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseDeleteTool._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._DeleteTool._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -661,32 +676,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _ExportTools(_BaseToolsRestTransport._BaseExportTools, ToolsRestStub):
+ class _ExportTools(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.ExportTools")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("ExportTools")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -716,34 +718,45 @@ def __call__(
"""
- http_options = _BaseToolsRestTransport._BaseExportTools._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/tools:export",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_export_tools(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseExportTools._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = tool.ExportToolsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseToolsRestTransport._BaseExportTools._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseExportTools._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._ExportTools._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -757,31 +770,19 @@ def __call__(
resp = self._interceptor.post_export_tools(resp)
return resp
- class _GetTool(_BaseToolsRestTransport._BaseGetTool, ToolsRestStub):
+ class _GetTool(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.GetTool")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetTool")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -814,27 +815,38 @@ def __call__(
"""
- http_options = _BaseToolsRestTransport._BaseGetTool._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_tool(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseGetTool._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = tool.GetToolRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseToolsRestTransport._BaseGetTool._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._GetTool._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -850,31 +862,19 @@ def __call__(
resp = self._interceptor.post_get_tool(resp)
return resp
- class _ListTools(_BaseToolsRestTransport._BaseListTools, ToolsRestStub):
+ class _ListTools(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.ListTools")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListTools")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -903,29 +903,38 @@ def __call__(
"""
- http_options = _BaseToolsRestTransport._BaseListTools._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/tools",
+ },
+ ]
request, metadata = self._interceptor.pre_list_tools(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseListTools._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = tool.ListToolsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseListTools._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._ListTools._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -941,32 +950,19 @@ def __call__(
resp = self._interceptor.post_list_tools(resp)
return resp
- class _UpdateTool(_BaseToolsRestTransport._BaseUpdateTool, ToolsRestStub):
+ class _UpdateTool(ToolsRestStub):
def __hash__(self):
- return hash("ToolsRestTransport.UpdateTool")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateTool")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -999,34 +995,45 @@ def __call__(
"""
- http_options = _BaseToolsRestTransport._BaseUpdateTool._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{tool.name=projects/*/locations/*/agents/*/tools/*}",
+ "body": "tool",
+ },
+ ]
request, metadata = self._interceptor.pre_update_tool(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseUpdateTool._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_tool.UpdateToolRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseToolsRestTransport._BaseUpdateTool._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseUpdateTool._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = ToolsRestTransport._UpdateTool._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1084,32 +1091,7 @@ def update_tool(self) -> Callable[[gcdc_tool.UpdateToolRequest], gcdc_tool.Tool]
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseToolsRestTransport._BaseGetLocation, ToolsRestStub):
- def __hash__(self):
- return hash("ToolsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(ToolsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1133,29 +1115,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = _BaseToolsRestTransport._BaseGetLocation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ToolsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1163,9 +1148,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1173,32 +1157,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(_BaseToolsRestTransport._BaseListLocations, ToolsRestStub):
- def __hash__(self):
- return hash("ToolsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(ToolsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1222,31 +1181,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseToolsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ToolsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1254,9 +1214,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1264,32 +1223,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(_BaseToolsRestTransport._BaseCancelOperation, ToolsRestStub):
- def __hash__(self):
- return hash("ToolsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(ToolsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1310,33 +1244,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseToolsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseToolsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ToolsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1350,32 +1289,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseToolsRestTransport._BaseGetOperation, ToolsRestStub):
- def __hash__(self):
- return hash("ToolsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(ToolsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1399,29 +1313,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = _BaseToolsRestTransport._BaseGetOperation._get_http_options()
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ToolsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1429,9 +1350,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1439,32 +1359,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(_BaseToolsRestTransport._BaseListOperations, ToolsRestStub):
- def __hash__(self):
- return hash("ToolsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(ToolsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1488,31 +1383,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseToolsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseToolsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseToolsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = ToolsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1520,9 +1420,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py
index 4dc0d02fba15..68df593ad54c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -212,7 +213,10 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = TransitionRouteGroupsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(TransitionRouteGroupsClient).get_transport_class,
+ type(TransitionRouteGroupsClient),
+ )
def __init__(
self,
@@ -404,8 +408,6 @@ async def sample_list_transition_route_groups():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -944,7 +946,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -997,7 +1003,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1053,7 +1063,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1103,7 +1117,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1156,7 +1174,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py
index 870709771730..622da6492ba2 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py
@@ -803,7 +803,7 @@ def __init__(
Type[TransitionRouteGroupsTransport],
Callable[..., TransitionRouteGroupsTransport],
] = (
- TransitionRouteGroupsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., TransitionRouteGroupsTransport], transport)
)
@@ -939,8 +939,6 @@ def sample_list_transition_route_groups():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1488,7 +1486,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1541,7 +1543,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1597,7 +1603,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1647,7 +1657,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1700,7 +1714,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py
index 12977e8c266d..248ab2be733b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import transition_route_group
@@ -65,8 +51,6 @@ def __init__(
request: transition_route_group.ListTransitionRouteGroupsRequest,
response: transition_route_group.ListTransitionRouteGroupsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = transition_route_group.ListTransitionRouteGroupsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -101,12 +80,7 @@ def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[transition_route_group.TransitionRouteGroup]:
@@ -143,8 +117,6 @@ def __init__(
request: transition_route_group.ListTransitionRouteGroupsRequest,
response: transition_route_group.ListTransitionRouteGroupsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -156,17 +128,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = transition_route_group.ListTransitionRouteGroupsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -179,12 +146,7 @@ async def pages(
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[transition_route_group.TransitionRouteGroup]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py
index eff4ccc48d91..b11197b381dd 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py
@@ -90,8 +90,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -104,7 +102,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -162,31 +160,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py
index 6a4010e44dab..766b8e1cea56 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py
@@ -128,8 +128,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py
index 1d02e798540b..3c53662dc945 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -176,8 +175,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -234,9 +232,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -421,70 +416,36 @@ def delete_transition_route_group(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_transition_route_groups: self._wrap_method(
+ self.list_transition_route_groups: gapic_v1.method_async.wrap_method(
self.list_transition_route_groups,
default_timeout=None,
client_info=client_info,
),
- self.get_transition_route_group: self._wrap_method(
+ self.get_transition_route_group: gapic_v1.method_async.wrap_method(
self.get_transition_route_group,
default_timeout=None,
client_info=client_info,
),
- self.create_transition_route_group: self._wrap_method(
+ self.create_transition_route_group: gapic_v1.method_async.wrap_method(
self.create_transition_route_group,
default_timeout=None,
client_info=client_info,
),
- self.update_transition_route_group: self._wrap_method(
+ self.update_transition_route_group: gapic_v1.method_async.wrap_method(
self.update_transition_route_group,
default_timeout=None,
client_info=client_info,
),
- self.delete_transition_route_group: self._wrap_method(
+ self.delete_transition_route_group: gapic_v1.method_async.wrap_method(
self.delete_transition_route_group,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/rest.py
index 3e95c8fa1b23..61f5075ac3ed 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/rest.py
@@ -16,33 +16,37 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+
+
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
from google.cloud.dialogflowcx_v3beta1.types import (
transition_route_group as gcdc_transition_route_group,
)
from google.cloud.dialogflowcx_v3beta1.types import transition_route_group
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseTransitionRouteGroupsRestTransport
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
-
+from .base import TransitionRouteGroupsTransport
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
@@ -347,8 +351,8 @@ class TransitionRouteGroupsRestStub:
_interceptor: TransitionRouteGroupsRestInterceptor
-class TransitionRouteGroupsRestTransport(_BaseTransitionRouteGroupsRestTransport):
- """REST backend synchronous transport for TransitionRouteGroups.
+class TransitionRouteGroupsRestTransport(TransitionRouteGroupsTransport):
+ """REST backend transport for TransitionRouteGroups.
Service for managing
[TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup].
@@ -358,6 +362,7 @@ class TransitionRouteGroupsRestTransport(_BaseTransitionRouteGroupsRestTransport
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -411,12 +416,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -427,35 +441,19 @@ def __init__(
self._interceptor = interceptor or TransitionRouteGroupsRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateTransitionRouteGroup(
- _BaseTransitionRouteGroupsRestTransport._BaseCreateTransitionRouteGroup,
- TransitionRouteGroupsRestStub,
- ):
+ class _CreateTransitionRouteGroup(TransitionRouteGroupsRestStub):
def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.CreateTransitionRouteGroup")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateTransitionRouteGroup")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -487,34 +485,56 @@ def __call__(
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseCreateTransitionRouteGroup._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/transitionRouteGroups",
+ "body": "transition_route_group",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/transitionRouteGroups",
+ "body": "transition_route_group",
+ },
+ ]
request, metadata = self._interceptor.pre_create_transition_route_group(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseCreateTransitionRouteGroup._get_transcoded_request(
- http_options, request
+ pb_request = (
+ gcdc_transition_route_group.CreateTransitionRouteGroupRequest.pb(
+ request
+ )
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseTransitionRouteGroupsRestTransport._BaseCreateTransitionRouteGroup._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseCreateTransitionRouteGroup._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TransitionRouteGroupsRestTransport._CreateTransitionRouteGroup._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -530,34 +550,19 @@ def __call__(
resp = self._interceptor.post_create_transition_route_group(resp)
return resp
- class _DeleteTransitionRouteGroup(
- _BaseTransitionRouteGroupsRestTransport._BaseDeleteTransitionRouteGroup,
- TransitionRouteGroupsRestStub,
- ):
+ class _DeleteTransitionRouteGroup(TransitionRouteGroupsRestStub):
def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.DeleteTransitionRouteGroup")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteTransitionRouteGroup")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -581,29 +586,46 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseDeleteTransitionRouteGroup._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}",
+ },
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/transitionRouteGroups/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_transition_route_group(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseDeleteTransitionRouteGroup._get_transcoded_request(
- http_options, request
+ pb_request = transition_route_group.DeleteTransitionRouteGroupRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseDeleteTransitionRouteGroup._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TransitionRouteGroupsRestTransport._DeleteTransitionRouteGroup._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -611,34 +633,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetTransitionRouteGroup(
- _BaseTransitionRouteGroupsRestTransport._BaseGetTransitionRouteGroup,
- TransitionRouteGroupsRestStub,
- ):
+ class _GetTransitionRouteGroup(TransitionRouteGroupsRestStub):
def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.GetTransitionRouteGroup")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetTransitionRouteGroup")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -670,29 +677,46 @@ def __call__(
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseGetTransitionRouteGroup._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/transitionRouteGroups/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_transition_route_group(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseGetTransitionRouteGroup._get_transcoded_request(
- http_options, request
+ pb_request = transition_route_group.GetTransitionRouteGroupRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseGetTransitionRouteGroup._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TransitionRouteGroupsRestTransport._GetTransitionRouteGroup._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -708,34 +732,19 @@ def __call__(
resp = self._interceptor.post_get_transition_route_group(resp)
return resp
- class _ListTransitionRouteGroups(
- _BaseTransitionRouteGroupsRestTransport._BaseListTransitionRouteGroups,
- TransitionRouteGroupsRestStub,
- ):
+ class _ListTransitionRouteGroups(TransitionRouteGroupsRestStub):
def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.ListTransitionRouteGroups")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListTransitionRouteGroups")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -765,29 +774,46 @@ def __call__(
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseListTransitionRouteGroups._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/transitionRouteGroups",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/transitionRouteGroups",
+ },
+ ]
request, metadata = self._interceptor.pre_list_transition_route_groups(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseListTransitionRouteGroups._get_transcoded_request(
- http_options, request
+ pb_request = transition_route_group.ListTransitionRouteGroupsRequest.pb(
+ request
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseListTransitionRouteGroups._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TransitionRouteGroupsRestTransport._ListTransitionRouteGroups._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -803,35 +829,19 @@ def __call__(
resp = self._interceptor.post_list_transition_route_groups(resp)
return resp
- class _UpdateTransitionRouteGroup(
- _BaseTransitionRouteGroupsRestTransport._BaseUpdateTransitionRouteGroup,
- TransitionRouteGroupsRestStub,
- ):
+ class _UpdateTransitionRouteGroup(TransitionRouteGroupsRestStub):
def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.UpdateTransitionRouteGroup")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateTransitionRouteGroup")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -863,34 +873,56 @@ def __call__(
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseUpdateTransitionRouteGroup._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{transition_route_group.name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}",
+ "body": "transition_route_group",
+ },
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{transition_route_group.name=projects/*/locations/*/agents/*/transitionRouteGroups/*}",
+ "body": "transition_route_group",
+ },
+ ]
request, metadata = self._interceptor.pre_update_transition_route_group(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseUpdateTransitionRouteGroup._get_transcoded_request(
- http_options, request
+ pb_request = (
+ gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.pb(
+ request
+ )
)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseTransitionRouteGroupsRestTransport._BaseUpdateTransitionRouteGroup._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseUpdateTransitionRouteGroup._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
+ )
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = TransitionRouteGroupsRestTransport._UpdateTransitionRouteGroup._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -964,35 +996,7 @@ def update_transition_route_group(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(
- _BaseTransitionRouteGroupsRestTransport._BaseGetLocation,
- TransitionRouteGroupsRestStub,
- ):
- def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(TransitionRouteGroupsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1016,27 +1020,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TransitionRouteGroupsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1044,9 +1053,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1054,35 +1062,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseTransitionRouteGroupsRestTransport._BaseListLocations,
- TransitionRouteGroupsRestStub,
- ):
- def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(TransitionRouteGroupsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1106,27 +1086,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TransitionRouteGroupsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1134,9 +1119,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1144,35 +1128,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseTransitionRouteGroupsRestTransport._BaseCancelOperation,
- TransitionRouteGroupsRestStub,
- ):
- def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(TransitionRouteGroupsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1193,31 +1149,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = (
- TransitionRouteGroupsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- )
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1231,35 +1194,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(
- _BaseTransitionRouteGroupsRestTransport._BaseGetOperation,
- TransitionRouteGroupsRestStub,
- ):
- def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(TransitionRouteGroupsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1283,27 +1218,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TransitionRouteGroupsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1311,9 +1255,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1321,35 +1264,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseTransitionRouteGroupsRestTransport._BaseListOperations,
- TransitionRouteGroupsRestStub,
- ):
- def __hash__(self):
- return hash("TransitionRouteGroupsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(TransitionRouteGroupsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1373,27 +1288,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseTransitionRouteGroupsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = _BaseTransitionRouteGroupsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = _BaseTransitionRouteGroupsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = TransitionRouteGroupsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1401,9 +1325,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py
index 85e499210512..d3a4a1214054 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -191,7 +192,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = VersionsClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(VersionsClient).get_transport_class, type(VersionsClient)
+ )
def __init__(
self,
@@ -375,8 +378,6 @@ async def sample_list_versions():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1140,7 +1141,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1193,7 +1198,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1249,7 +1258,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1299,7 +1312,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1352,7 +1369,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/client.py
index 63e2bb9b9ea4..24e9d8e35bbe 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/client.py
@@ -672,7 +672,7 @@ def __init__(
transport_init: Union[
Type[VersionsTransport], Callable[..., VersionsTransport]
] = (
- VersionsClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., VersionsTransport], transport)
)
@@ -802,8 +802,6 @@ def sample_list_versions():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1562,7 +1560,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1615,7 +1617,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1671,7 +1677,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1721,7 +1731,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1774,7 +1788,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py
index e36b53bd6079..cfb9335357a9 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import version
@@ -65,8 +51,6 @@ def __init__(
request: version.ListVersionsRequest,
response: version.ListVersionsResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListVersionsResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = version.ListVersionsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[version.ListVersionsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[version.Version]:
@@ -139,8 +113,6 @@ def __init__(
request: version.ListVersionsRequest,
response: version.ListVersionsResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListVersionsResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = version.ListVersionsRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[version.ListVersionsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[version.Version]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py
index 4cad8f0962cb..7cd56e79a8da 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -170,31 +168,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py
index fa028219d6f5..dc122e47e873 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py
@@ -127,8 +127,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py
index 235f009a6f16..61786423a696 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -175,8 +174,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -233,9 +231,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -482,80 +477,46 @@ def compare_versions(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_versions: self._wrap_method(
+ self.list_versions: gapic_v1.method_async.wrap_method(
self.list_versions,
default_timeout=None,
client_info=client_info,
),
- self.get_version: self._wrap_method(
+ self.get_version: gapic_v1.method_async.wrap_method(
self.get_version,
default_timeout=None,
client_info=client_info,
),
- self.create_version: self._wrap_method(
+ self.create_version: gapic_v1.method_async.wrap_method(
self.create_version,
default_timeout=None,
client_info=client_info,
),
- self.update_version: self._wrap_method(
+ self.update_version: gapic_v1.method_async.wrap_method(
self.update_version,
default_timeout=None,
client_info=client_info,
),
- self.delete_version: self._wrap_method(
+ self.delete_version: gapic_v1.method_async.wrap_method(
self.delete_version,
default_timeout=None,
client_info=client_info,
),
- self.load_version: self._wrap_method(
+ self.load_version: gapic_v1.method_async.wrap_method(
self.load_version,
default_timeout=None,
client_info=client_info,
),
- self.compare_versions: self._wrap_method(
+ self.compare_versions: gapic_v1.method_async.wrap_method(
self.compare_versions,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/rest.py
index 5ed8ecc84437..7bfe1c1a6b55 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/versions/transports/rest.py
@@ -16,32 +16,42 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
-from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
+from google.api_core import (
+ gapic_v1,
+ operations_v1,
+ path_template,
+ rest_helpers,
+ rest_streaming,
+)
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import version
-from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseVersionsRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import version
+from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import VersionsTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -383,8 +393,8 @@ class VersionsRestStub:
_interceptor: VersionsRestInterceptor
-class VersionsRestTransport(_BaseVersionsRestTransport):
- """REST backend synchronous transport for Versions.
+class VersionsRestTransport(VersionsTransport):
+ """REST backend transport for Versions.
Service for managing
[Versions][google.cloud.dialogflow.cx.v3beta1.Version].
@@ -394,6 +404,7 @@ class VersionsRestTransport(_BaseVersionsRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -447,12 +458,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -522,34 +542,19 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
- class _CompareVersions(
- _BaseVersionsRestTransport._BaseCompareVersions, VersionsRestStub
- ):
+ class _CompareVersions(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.CompareVersions")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CompareVersions")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -578,40 +583,47 @@ def __call__(
"""
- http_options = (
- _BaseVersionsRestTransport._BaseCompareVersions._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{base_version=projects/*/locations/*/agents/*/flows/*/versions/*}:compareVersions",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_compare_versions(
request, metadata
)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseCompareVersions._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = version.CompareVersionsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = (
- _BaseVersionsRestTransport._BaseCompareVersions._get_request_body_json(
- transcoded_request
- )
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseCompareVersions._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._CompareVersions._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -627,34 +639,19 @@ def __call__(
resp = self._interceptor.post_compare_versions(resp)
return resp
- class _CreateVersion(
- _BaseVersionsRestTransport._BaseCreateVersion, VersionsRestStub
- ):
+ class _CreateVersion(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.CreateVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -684,36 +681,45 @@ def __call__(
"""
- http_options = (
- _BaseVersionsRestTransport._BaseCreateVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/versions",
+ "body": "version",
+ },
+ ]
request, metadata = self._interceptor.pre_create_version(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseCreateVersion._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_version.CreateVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseVersionsRestTransport._BaseCreateVersion._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseCreateVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._CreateVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -727,33 +733,19 @@ def __call__(
resp = self._interceptor.post_create_version(resp)
return resp
- class _DeleteVersion(
- _BaseVersionsRestTransport._BaseDeleteVersion, VersionsRestStub
- ):
+ class _DeleteVersion(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.DeleteVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -776,31 +768,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseDeleteVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/versions/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_version(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseDeleteVersion._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = version.DeleteVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseDeleteVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._DeleteVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -808,31 +807,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetVersion(_BaseVersionsRestTransport._BaseGetVersion, VersionsRestStub):
+ class _GetVersion(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.GetVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -859,31 +846,38 @@ def __call__(
Represents a version of a flow.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseGetVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/versions/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_version(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseGetVersion._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = version.GetVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseGetVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._GetVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -899,31 +893,19 @@ def __call__(
resp = self._interceptor.post_get_version(resp)
return resp
- class _ListVersions(_BaseVersionsRestTransport._BaseListVersions, VersionsRestStub):
+ class _ListVersions(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.ListVersions")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListVersions")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -952,31 +934,38 @@ def __call__(
"""
- http_options = (
- _BaseVersionsRestTransport._BaseListVersions._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/versions",
+ },
+ ]
request, metadata = self._interceptor.pre_list_versions(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseListVersions._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = version.ListVersionsRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseListVersions._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._ListVersions._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -992,32 +981,19 @@ def __call__(
resp = self._interceptor.post_list_versions(resp)
return resp
- class _LoadVersion(_BaseVersionsRestTransport._BaseLoadVersion, VersionsRestStub):
+ class _LoadVersion(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.LoadVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("LoadVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1047,36 +1023,45 @@ def __call__(
"""
- http_options = (
- _BaseVersionsRestTransport._BaseLoadVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/versions/*}:load",
+ "body": "*",
+ },
+ ]
request, metadata = self._interceptor.pre_load_version(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseLoadVersion._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = version.LoadVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseVersionsRestTransport._BaseLoadVersion._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseLoadVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._LoadVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1090,34 +1075,21 @@ def __call__(
resp = self._interceptor.post_load_version(resp)
return resp
- class _UpdateVersion(
- _BaseVersionsRestTransport._BaseUpdateVersion, VersionsRestStub
- ):
+ class _UpdateVersion(VersionsRestStub):
def __hash__(self):
- return hash("VersionsRestTransport.UpdateVersion")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateVersion")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "updateMask": {},
+ }
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -1144,36 +1116,45 @@ def __call__(
Represents a version of a flow.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseUpdateVersion._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{version.name=projects/*/locations/*/agents/*/flows/*/versions/*}",
+ "body": "version",
+ },
+ ]
request, metadata = self._interceptor.pre_update_version(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseUpdateVersion._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_version.UpdateVersionRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseVersionsRestTransport._BaseUpdateVersion._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseUpdateVersion._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = VersionsRestTransport._UpdateVersion._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1247,32 +1228,7 @@ def update_version(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseVersionsRestTransport._BaseGetLocation, VersionsRestStub):
- def __hash__(self):
- return hash("VersionsRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(VersionsRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -1296,31 +1252,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = VersionsRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1328,9 +1285,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1338,34 +1294,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseVersionsRestTransport._BaseListLocations, VersionsRestStub
- ):
- def __hash__(self):
- return hash("VersionsRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(VersionsRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1389,31 +1318,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = VersionsRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1421,9 +1351,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1431,34 +1360,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseVersionsRestTransport._BaseCancelOperation, VersionsRestStub
- ):
- def __hash__(self):
- return hash("VersionsRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(VersionsRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1479,33 +1381,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = VersionsRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1519,32 +1426,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseVersionsRestTransport._BaseGetOperation, VersionsRestStub):
- def __hash__(self):
- return hash("VersionsRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(VersionsRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1568,31 +1450,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = VersionsRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1600,9 +1487,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1610,34 +1496,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseVersionsRestTransport._BaseListOperations, VersionsRestStub
- ):
- def __hash__(self):
- return hash("VersionsRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(VersionsRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1661,31 +1520,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseVersionsRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseVersionsRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseVersionsRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = VersionsRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1693,9 +1557,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py
index 5d4b5777e6c4..f3d5004aee26 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from collections import OrderedDict
+import functools
import re
from typing import (
Callable,
@@ -188,7 +189,9 @@ def universe_domain(self) -> str:
"""
return self._client._universe_domain
- get_transport_class = WebhooksClient.get_transport_class
+ get_transport_class = functools.partial(
+ type(WebhooksClient).get_transport_class, type(WebhooksClient)
+ )
def __init__(
self,
@@ -370,8 +373,6 @@ async def sample_list_webhooks():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -864,7 +865,11 @@ async def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -917,7 +922,11 @@ async def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -973,7 +982,11 @@ async def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1023,7 +1036,11 @@ async def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.get_location]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1076,7 +1093,11 @@ async def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self.transport._wrapped_methods[self._client._transport.list_locations]
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py
index af2a057c921d..d4faa64ef7ee 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py
@@ -689,7 +689,7 @@ def __init__(
transport_init: Union[
Type[WebhooksTransport], Callable[..., WebhooksTransport]
] = (
- WebhooksClient.get_transport_class(transport)
+ type(self).get_transport_class(transport)
if isinstance(transport, str) or transport is None
else cast(Callable[..., WebhooksTransport], transport)
)
@@ -817,8 +817,6 @@ def sample_list_webhooks():
method=rpc,
request=request,
response=response,
- retry=retry,
- timeout=timeout,
metadata=metadata,
)
@@ -1312,7 +1310,11 @@ def list_operations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_operations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_operations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1365,7 +1367,11 @@ def get_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1421,7 +1427,11 @@ def cancel_operation(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.cancel_operation,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1471,7 +1481,11 @@ def get_location(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.get_location]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.get_location,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1524,7 +1538,11 @@ def list_locations(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = self._transport._wrapped_methods[self._transport.list_locations]
+ rpc = gapic_v1.method.wrap_method(
+ self._transport.list_locations,
+ default_timeout=None,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
# Certain fields should be provided within the metadata header;
# add these here.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py
index 59caadaa03c9..ccb0865c041e 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py
@@ -22,22 +22,8 @@
Optional,
Sequence,
Tuple,
- Union,
)
-from google.api_core import gapic_v1
-from google.api_core import retry as retries
-from google.api_core import retry_async as retries_async
-
-try:
- OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
- OptionalAsyncRetry = Union[
- retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
- ]
-except AttributeError: # pragma: NO COVER
- OptionalRetry = Union[retries.Retry, object, None] # type: ignore
- OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
-
from google.cloud.dialogflowcx_v3beta1.types import webhook
@@ -65,8 +51,6 @@ def __init__(
request: webhook.ListWebhooksRequest,
response: webhook.ListWebhooksResponse,
*,
- retry: OptionalRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -78,17 +62,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse):
The initial response object.
- retry (google.api_core.retry.Retry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = webhook.ListWebhooksRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -99,12 +78,7 @@ def pages(self) -> Iterator[webhook.ListWebhooksResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[webhook.Webhook]:
@@ -139,8 +113,6 @@ def __init__(
request: webhook.ListWebhooksRequest,
response: webhook.ListWebhooksResponse,
*,
- retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
- timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
@@ -152,17 +124,12 @@ def __init__(
The initial request object.
response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse):
The initial response object.
- retry (google.api_core.retry.AsyncRetry): Designation of what errors,
- if any, should be retried.
- timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = webhook.ListWebhooksRequest(request)
self._response = response
- self._retry = retry
- self._timeout = timeout
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
@@ -173,12 +140,7 @@ async def pages(self) -> AsyncIterator[webhook.ListWebhooksResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = await self._method(
- self._request,
- retry=self._retry,
- timeout=self._timeout,
- metadata=self._metadata,
- )
+ self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterator[webhook.Webhook]:
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py
index 2474abafe17e..bff43fa1d284 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py
@@ -88,8 +88,6 @@ def __init__(
# Save the scopes.
self._scopes = scopes
- if not hasattr(self, "_ignore_credentials"):
- self._ignore_credentials: bool = False
# If no credentials are provided, then determine the appropriate
# defaults.
@@ -102,7 +100,7 @@ def __init__(
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
- elif credentials is None and not self._ignore_credentials:
+ elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
@@ -160,31 +158,6 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
- self.get_location: gapic_v1.method.wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: gapic_v1.method.wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: gapic_v1.method.wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: gapic_v1.method.wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: gapic_v1.method.wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
def close(self):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py
index 40d5f0525db1..a0e3fc531cd7 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py
@@ -126,8 +126,7 @@ def __init__(
if isinstance(channel, grpc.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py
index 429ca056c10e..3c8c13a38f1c 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py
@@ -13,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-import inspect
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
import warnings
@@ -174,8 +173,7 @@ def __init__(
if isinstance(channel, aio.Channel):
# Ignore credentials if a channel was passed.
- credentials = None
- self._ignore_credentials = True
+ credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
@@ -232,9 +230,6 @@ def __init__(
)
# Wrap messages. This must be done after self._grpc_channel exists
- self._wrap_with_kind = (
- "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
- )
self._prep_wrapped_messages(client_info)
@property
@@ -383,70 +378,36 @@ def delete_webhook(
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
- self.list_webhooks: self._wrap_method(
+ self.list_webhooks: gapic_v1.method_async.wrap_method(
self.list_webhooks,
default_timeout=None,
client_info=client_info,
),
- self.get_webhook: self._wrap_method(
+ self.get_webhook: gapic_v1.method_async.wrap_method(
self.get_webhook,
default_timeout=None,
client_info=client_info,
),
- self.create_webhook: self._wrap_method(
+ self.create_webhook: gapic_v1.method_async.wrap_method(
self.create_webhook,
default_timeout=None,
client_info=client_info,
),
- self.update_webhook: self._wrap_method(
+ self.update_webhook: gapic_v1.method_async.wrap_method(
self.update_webhook,
default_timeout=None,
client_info=client_info,
),
- self.delete_webhook: self._wrap_method(
+ self.delete_webhook: gapic_v1.method_async.wrap_method(
self.delete_webhook,
default_timeout=None,
client_info=client_info,
),
- self.get_location: self._wrap_method(
- self.get_location,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_locations: self._wrap_method(
- self.list_locations,
- default_timeout=None,
- client_info=client_info,
- ),
- self.cancel_operation: self._wrap_method(
- self.cancel_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.get_operation: self._wrap_method(
- self.get_operation,
- default_timeout=None,
- client_info=client_info,
- ),
- self.list_operations: self._wrap_method(
- self.list_operations,
- default_timeout=None,
- client_info=client_info,
- ),
}
- def _wrap_method(self, func, *args, **kwargs):
- if self._wrap_with_kind: # pragma: NO COVER
- kwargs["kind"] = self.kind
- return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
-
def close(self):
return self.grpc_channel.close()
- @property
- def kind(self) -> str:
- return "grpc_asyncio"
-
@property
def cancel_operation(
self,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/rest.py
index 8e6b6e6dff9f..5ea5619f8a7b 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/rest.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/rest.py
@@ -16,32 +16,36 @@
import dataclasses
import json # type: ignore
+import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
+from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
-from google.api_core import gapic_v1, rest_helpers, rest_streaming
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.transport.requests import AuthorizedSession # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
-from google.longrunning import operations_pb2 # type: ignore
-from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import json_format
+import grpc # type: ignore
from requests import __version__ as requests_version
-from google.cloud.dialogflowcx_v3beta1.types import webhook
-from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook
-
-from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
-from .rest_base import _BaseWebhooksRestTransport
-
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
+
+from google.cloud.dialogflowcx_v3beta1.types import webhook
+from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .base import WebhooksTransport
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
@@ -323,8 +327,8 @@ class WebhooksRestStub:
_interceptor: WebhooksRestInterceptor
-class WebhooksRestTransport(_BaseWebhooksRestTransport):
- """REST backend synchronous transport for Webhooks.
+class WebhooksRestTransport(WebhooksTransport):
+ """REST backend transport for Webhooks.
Service for managing
[Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook].
@@ -334,6 +338,7 @@ class WebhooksRestTransport(_BaseWebhooksRestTransport):
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
+
"""
def __init__(
@@ -387,12 +392,21 @@ def __init__(
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
+ maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host)
+ if maybe_url_match is None:
+ raise ValueError(
+ f"Unexpected hostname structure: {host}"
+ ) # pragma: NO COVER
+
+ url_match_items = maybe_url_match.groupdict()
+
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
+
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
- url_scheme=url_scheme,
api_audience=api_audience,
)
self._session = AuthorizedSession(
@@ -403,34 +417,19 @@ def __init__(
self._interceptor = interceptor or WebhooksRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _CreateWebhook(
- _BaseWebhooksRestTransport._BaseCreateWebhook, WebhooksRestStub
- ):
+ class _CreateWebhook(WebhooksRestStub):
def __hash__(self):
- return hash("WebhooksRestTransport.CreateWebhook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("CreateWebhook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -464,36 +463,45 @@ def __call__(
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseCreateWebhook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/webhooks",
+ "body": "webhook",
+ },
+ ]
request, metadata = self._interceptor.pre_create_webhook(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseCreateWebhook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_webhook.CreateWebhookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ # Jsonify the request body
- body = _BaseWebhooksRestTransport._BaseCreateWebhook._get_request_body_json(
- transcoded_request
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseCreateWebhook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = WebhooksRestTransport._CreateWebhook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -509,33 +517,19 @@ def __call__(
resp = self._interceptor.post_create_webhook(resp)
return resp
- class _DeleteWebhook(
- _BaseWebhooksRestTransport._BaseDeleteWebhook, WebhooksRestStub
- ):
+ class _DeleteWebhook(WebhooksRestStub):
def __hash__(self):
- return hash("WebhooksRestTransport.DeleteWebhook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("DeleteWebhook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -558,31 +552,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseDeleteWebhook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "delete",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/webhooks/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_delete_webhook(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseDeleteWebhook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = webhook.DeleteWebhookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseDeleteWebhook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = WebhooksRestTransport._DeleteWebhook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -590,31 +591,19 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- class _GetWebhook(_BaseWebhooksRestTransport._BaseGetWebhook, WebhooksRestStub):
+ class _GetWebhook(WebhooksRestStub):
def __hash__(self):
- return hash("WebhooksRestTransport.GetWebhook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("GetWebhook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -648,31 +637,38 @@ def __call__(
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseGetWebhook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/agents/*/webhooks/*}",
+ },
+ ]
request, metadata = self._interceptor.pre_get_webhook(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseGetWebhook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = webhook.GetWebhookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseGetWebhook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = WebhooksRestTransport._GetWebhook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -688,31 +684,19 @@ def __call__(
resp = self._interceptor.post_get_webhook(resp)
return resp
- class _ListWebhooks(_BaseWebhooksRestTransport._BaseListWebhooks, WebhooksRestStub):
+ class _ListWebhooks(WebhooksRestStub):
def __hash__(self):
- return hash("WebhooksRestTransport.ListWebhooks")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
+ return hash("ListWebhooks")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -741,31 +725,38 @@ def __call__(
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseListWebhooks._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{parent=projects/*/locations/*/agents/*}/webhooks",
+ },
+ ]
request, metadata = self._interceptor.pre_list_webhooks(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseListWebhooks._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = webhook.ListWebhooksRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseListWebhooks._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = WebhooksRestTransport._ListWebhooks._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -781,34 +772,19 @@ def __call__(
resp = self._interceptor.post_list_webhooks(resp)
return resp
- class _UpdateWebhook(
- _BaseWebhooksRestTransport._BaseUpdateWebhook, WebhooksRestStub
- ):
+ class _UpdateWebhook(WebhooksRestStub):
def __hash__(self):
- return hash("WebhooksRestTransport.UpdateWebhook")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- data=body,
- )
- return response
+ return hash("UpdateWebhook")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
+
+ @classmethod
+ def _get_unset_required_fields(cls, message_dict):
+ return {
+ k: v
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
+ if k not in message_dict
+ }
def __call__(
self,
@@ -842,36 +818,45 @@ def __call__(
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseUpdateWebhook._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "patch",
+ "uri": "/v3beta1/{webhook.name=projects/*/locations/*/agents/*/webhooks/*}",
+ "body": "webhook",
+ },
+ ]
request, metadata = self._interceptor.pre_update_webhook(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseUpdateWebhook._get_transcoded_request(
- http_options, request
- )
- )
+ pb_request = gcdc_webhook.UpdateWebhookRequest.pb(request)
+ transcoded_request = path_template.transcode(http_options, pb_request)
- body = _BaseWebhooksRestTransport._BaseUpdateWebhook._get_request_body_json(
- transcoded_request
+ # Jsonify the request body
+
+ body = json_format.MessageToJson(
+ transcoded_request["body"], use_integers_for_enums=True
)
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseUpdateWebhook._get_query_params_json(
- transcoded_request
+ query_params = json.loads(
+ json_format.MessageToJson(
+ transcoded_request["query_params"],
+ use_integers_for_enums=True,
)
)
+ query_params.update(self._get_unset_required_fields(query_params))
+
+ query_params["$alt"] = "json;enum-encoding=int"
# Send the request
- response = WebhooksRestTransport._UpdateWebhook._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
- body,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
+ data=body,
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -929,32 +914,7 @@ def update_webhook(
def get_location(self):
return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore
- class _GetLocation(_BaseWebhooksRestTransport._BaseGetLocation, WebhooksRestStub):
- def __hash__(self):
- return hash("WebhooksRestTransport.GetLocation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetLocation(WebhooksRestStub):
def __call__(
self,
request: locations_pb2.GetLocationRequest,
@@ -978,31 +938,32 @@ def __call__(
locations_pb2.Location: Response from GetLocation method.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseGetLocation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_location(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseGetLocation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseGetLocation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = WebhooksRestTransport._GetLocation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1010,9 +971,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.Location()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_location(resp)
return resp
@@ -1020,34 +980,7 @@ def __call__(
def list_locations(self):
return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore
- class _ListLocations(
- _BaseWebhooksRestTransport._BaseListLocations, WebhooksRestStub
- ):
- def __hash__(self):
- return hash("WebhooksRestTransport.ListLocations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListLocations(WebhooksRestStub):
def __call__(
self,
request: locations_pb2.ListLocationsRequest,
@@ -1071,31 +1004,32 @@ def __call__(
locations_pb2.ListLocationsResponse: Response from ListLocations method.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseListLocations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/locations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_locations(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseListLocations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseListLocations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = WebhooksRestTransport._ListLocations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1103,9 +1037,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = locations_pb2.ListLocationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_locations(resp)
return resp
@@ -1113,34 +1046,7 @@ def __call__(
def cancel_operation(self):
return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore
- class _CancelOperation(
- _BaseWebhooksRestTransport._BaseCancelOperation, WebhooksRestStub
- ):
- def __hash__(self):
- return hash("WebhooksRestTransport.CancelOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _CancelOperation(WebhooksRestStub):
def __call__(
self,
request: operations_pb2.CancelOperationRequest,
@@ -1161,33 +1067,38 @@ def __call__(
sent along with the request as metadata.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseCancelOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/operations/*}:cancel",
+ },
+ {
+ "method": "post",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}:cancel",
+ },
+ ]
+
request, metadata = self._interceptor.pre_cancel_operation(
request, metadata
)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseCancelOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseCancelOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = WebhooksRestTransport._CancelOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1201,32 +1112,7 @@ def __call__(
def get_operation(self):
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
- class _GetOperation(_BaseWebhooksRestTransport._BaseGetOperation, WebhooksRestStub):
- def __hash__(self):
- return hash("WebhooksRestTransport.GetOperation")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _GetOperation(WebhooksRestStub):
def __call__(
self,
request: operations_pb2.GetOperationRequest,
@@ -1250,31 +1136,36 @@ def __call__(
operations_pb2.Operation: Response from GetOperation method.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseGetOperation._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/operations/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*/operations/*}",
+ },
+ ]
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseGetOperation._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseGetOperation._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = WebhooksRestTransport._GetOperation._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1282,9 +1173,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.Operation()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_get_operation(resp)
return resp
@@ -1292,34 +1182,7 @@ def __call__(
def list_operations(self):
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
- class _ListOperations(
- _BaseWebhooksRestTransport._BaseListOperations, WebhooksRestStub
- ):
- def __hash__(self):
- return hash("WebhooksRestTransport.ListOperations")
-
- @staticmethod
- def _get_response(
- host,
- metadata,
- query_params,
- session,
- timeout,
- transcoded_request,
- body=None,
- ):
- uri = transcoded_request["uri"]
- method = transcoded_request["method"]
- headers = dict(metadata)
- headers["Content-Type"] = "application/json"
- response = getattr(session, method)(
- "{host}{uri}".format(host=host, uri=uri),
- timeout=timeout,
- headers=headers,
- params=rest_helpers.flatten_query_params(query_params, strict=True),
- )
- return response
-
+ class _ListOperations(WebhooksRestStub):
def __call__(
self,
request: operations_pb2.ListOperationsRequest,
@@ -1343,31 +1206,36 @@ def __call__(
operations_pb2.ListOperationsResponse: Response from ListOperations method.
"""
- http_options = (
- _BaseWebhooksRestTransport._BaseListOperations._get_http_options()
- )
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*}/operations",
+ },
+ {
+ "method": "get",
+ "uri": "/v3beta1/{name=projects/*/locations/*}/operations",
+ },
+ ]
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
- transcoded_request = (
- _BaseWebhooksRestTransport._BaseListOperations._get_transcoded_request(
- http_options, request
- )
- )
+ request_kwargs = json_format.MessageToDict(request)
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
+
+ uri = transcoded_request["uri"]
+ method = transcoded_request["method"]
# Jsonify the query params
- query_params = (
- _BaseWebhooksRestTransport._BaseListOperations._get_query_params_json(
- transcoded_request
- )
- )
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
# Send the request
- response = WebhooksRestTransport._ListOperations._get_response(
- self._host,
- metadata,
- query_params,
- self._session,
- timeout,
- transcoded_request,
+ headers = dict(metadata)
+ headers["Content-Type"] = "application/json"
+
+ response = getattr(self._session, method)(
+ "{host}{uri}".format(host=self._host, uri=uri),
+ timeout=timeout,
+ headers=headers,
+ params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
@@ -1375,9 +1243,8 @@ def __call__(
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
- content = response.content.decode("utf-8")
resp = operations_pb2.ListOperationsResponse()
- resp = json_format.Parse(content, resp)
+ resp = json_format.Parse(response.content.decode("utf-8"), resp)
resp = self._interceptor.post_list_operations(resp)
return resp
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/advanced_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/advanced_settings.py
index 2c9e8d39bbec..f7efb34d9bba 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/advanced_settings.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/advanced_settings.py
@@ -171,14 +171,11 @@ class LoggingSettings(proto.Message):
Attributes:
enable_stackdriver_logging (bool):
- Enables Google Cloud Logging.
+ If true, StackDriver logging is currently
+ enabled.
enable_interaction_logging (bool):
- Enables DF Interaction logging.
- enable_consent_based_redaction (bool):
- Enables consent-based end-user input redaction, if true, a
- pre-defined session parameter
- ``$session.params.conversation-redaction`` will be used to
- determine if the utterance should be redacted.
+ If true, DF Interaction logging is currently
+ enabled.
"""
enable_stackdriver_logging: bool = proto.Field(
@@ -189,10 +186,6 @@ class LoggingSettings(proto.Message):
proto.BOOL,
number=3,
)
- enable_consent_based_redaction: bool = proto.Field(
- proto.BOOL,
- number=4,
- )
audio_export_gcs_destination: gcs.GcsDestination = proto.Field(
proto.MESSAGE,
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/data_store_connection.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/data_store_connection.py
index 22838605aaeb..5dad10daf2f4 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/data_store_connection.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/data_store_connection.py
@@ -122,11 +122,6 @@ class RewriterModelCallSignals(proto.Message):
Prompt as sent to the model.
model_output (str):
Output of the generative model.
- model (str):
- Name of the generative model. For example,
- "gemini-ultra", "gemini-pro", "gemini-1.5-flash"
- etc. Defaults to "Other" if the model is
- unknown.
"""
rendered_prompt: str = proto.Field(
@@ -137,10 +132,6 @@ class RewriterModelCallSignals(proto.Message):
proto.STRING,
number=2,
)
- model: str = proto.Field(
- proto.STRING,
- number=3,
- )
class SearchSnippet(proto.Message):
r"""Search snippet details.
@@ -176,11 +167,6 @@ class AnswerGenerationModelCallSignals(proto.Message):
Prompt as sent to the model.
model_output (str):
Output of the generative model.
- model (str):
- Name of the generative model. For example,
- "gemini-ultra", "gemini-pro", "gemini-1.5-flash"
- etc. Defaults to "Other" if the model is
- unknown.
"""
rendered_prompt: str = proto.Field(
@@ -191,10 +177,6 @@ class AnswerGenerationModelCallSignals(proto.Message):
proto.STRING,
number=2,
)
- model: str = proto.Field(
- proto.STRING,
- number=3,
- )
class AnswerPart(proto.Message):
r"""Answer part with citation.
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/flow.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/flow.py
index ca0688fdb1ec..59e22fe3b176 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/flow.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/flow.py
@@ -215,10 +215,6 @@ class Flow(proto.Message):
multi_language_settings (google.cloud.dialogflowcx_v3beta1.types.Flow.MultiLanguageSettings):
Optional. Multi-lingual agent settings for
this flow.
- locked (bool):
- Indicates whether the flow is locked for
- changes. If the flow is locked, modifications to
- the flow will be rejected.
"""
class MultiLanguageSettings(proto.Message):
@@ -296,10 +292,6 @@ class MultiLanguageSettings(proto.Message):
number=28,
message=MultiLanguageSettings,
)
- locked: bool = proto.Field(
- proto.BOOL,
- number=30,
- )
class CreateFlowRequest(proto.Message):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/page.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/page.py
index 8f25400ff977..5102c155d4fa 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/page.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/page.py
@@ -401,11 +401,6 @@ class EventHandler(proto.Message):
The target flow to transition to. Format:
``projects//locations//agents//flows/``.
- This field is a member of `oneof`_ ``target``.
- target_playbook (str):
- The target playbook to transition to. Format:
- ``projects//locations//agents//playbooks/``.
-
This field is a member of `oneof`_ ``target``.
"""
@@ -432,11 +427,6 @@ class EventHandler(proto.Message):
number=3,
oneof="target",
)
- target_playbook: str = proto.Field(
- proto.STRING,
- number=7,
- oneof="target",
- )
class TransitionRoute(proto.Message):
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py
index c113134acdb2..57422e5717ac 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py
@@ -1782,9 +1782,6 @@ class MatchType(proto.Enum):
Indicates an empty query.
EVENT (6):
The query directly triggered an event.
- KNOWLEDGE_CONNECTOR (8):
- The query was matched to a Knowledge
- Connector answer.
PLAYBOOK (9):
The query was handled by a
[``Playbook``][google.cloud.dialogflow.cx.v3beta1.Playbook].
@@ -1796,7 +1793,6 @@ class MatchType(proto.Enum):
NO_MATCH = 4
NO_INPUT = 5
EVENT = 6
- KNOWLEDGE_CONNECTOR = 8
PLAYBOOK = 9
intent: gcdc_intent.Intent = proto.Field(
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/test_case.py
index 8bd05dc64a62..d9cbb569b151 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/test_case.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/test_case.py
@@ -222,18 +222,20 @@ class TestConfig(proto.Message):
``projects//locations//agents//flows/``.
Only one of ``flow`` and ``page`` should be set to indicate
- the starting point of the test case. If neither is set, the
- test case will start with start page on the default start
- flow.
+ the starting point of the test case. If both are set,
+ ``page`` takes precedence over ``flow``. If neither is set,
+ the test case will start with start page on the default
+ start flow.
page (str):
The [page][google.cloud.dialogflow.cx.v3beta1.Page] to start
the test case with. Format:
``projects//locations//agents//flows//pages/``.
Only one of ``flow`` and ``page`` should be set to indicate
- the starting point of the test case. If neither is set, the
- test case will start with start page on the default start
- flow.
+ the starting point of the test case. If both are set,
+ ``page`` takes precedence over ``flow``. If neither is set,
+ the test case will start with start page on the default
+ start flow.
"""
tracking_parameters: MutableSequence[str] = proto.RepeatedField(
diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/tool.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/tool.py
index 1b27c370b4db..f9761ae383d4 100644
--- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/tool.py
+++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/tool.py
@@ -390,8 +390,6 @@ class OpenApiTool(proto.Message):
tls_config (google.cloud.dialogflowcx_v3beta1.types.Tool.TLSConfig):
Optional. TLS configuration for the HTTPS
verification.
- service_directory_config (google.cloud.dialogflowcx_v3beta1.types.Tool.ServiceDirectoryConfig):
- Optional. Service Directory configuration.
"""
text_schema: str = proto.Field(
@@ -409,11 +407,6 @@ class OpenApiTool(proto.Message):
number=3,
message="Tool.TLSConfig",
)
- service_directory_config: "Tool.ServiceDirectoryConfig" = proto.Field(
- proto.MESSAGE,
- number=4,
- message="Tool.ServiceDirectoryConfig",
- )
class DataStoreTool(proto.Message):
r"""A DataStoreTool is a way to provide specifications needed to
@@ -695,24 +688,6 @@ class CACert(proto.Message):
message="Tool.TLSConfig.CACert",
)
- class ServiceDirectoryConfig(proto.Message):
- r"""Configuration for tools using Service Directory.
-
- Attributes:
- service (str):
- Required. The name of `Service
- Directory `__
- service. Format:
- ``projects//locations//namespaces//services/``.
- ``LocationID`` of the service directory must be the same as
- the location of the agent.
- """
-
- service: str = proto.Field(
- proto.STRING,
- number=1,
- )
-
name: str = proto.Field(
proto.STRING,
number=1,
diff --git a/packages/google-cloud-dialogflow-cx/noxfile.py b/packages/google-cloud-dialogflow-cx/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-dialogflow-cx/noxfile.py
+++ b/packages/google-cloud-dialogflow-cx/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-dialogflow-cx/scripts/decrypt-secrets.sh b/packages/google-cloud-dialogflow-cx/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-dialogflow-cx/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-dialogflow-cx/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-dialogflow-cx/setup.py b/packages/google-cloud-dialogflow-cx/setup.py
index 7c5cb5846df3..ac938cbe9e27 100644
--- a/packages/google-cloud-dialogflow-cx/setup.py
+++ b/packages/google-cloud-dialogflow-cx/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-dialogflow-cx/testing/constraints-3.13.txt b/packages/google-cloud-dialogflow-cx/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-dialogflow-cx/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py
index 69b011ae1154..d85d450daf2d 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -65,7 +47,15 @@
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.agents import (
AgentsAsyncClient,
@@ -84,24 +74,10 @@
from google.cloud.dialogflowcx_v3beta1.types import safety_settings
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1134,6 +1110,25 @@ def test_list_agents(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_agents_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_agents), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_agents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ListAgentsRequest()
+
+
def test_list_agents_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1199,6 +1194,29 @@ def test_list_agents_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_agents_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_agents), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ agent.ListAgentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_agents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ListAgentsRequest()
+
+
@pytest.mark.asyncio
async def test_list_agents_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1207,7 +1225,7 @@ async def test_list_agents_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1222,23 +1240,27 @@ async def test_list_agents_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_agents
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_agents(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_agents(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1246,7 +1268,7 @@ async def test_list_agents_async(
transport: str = "grpc_asyncio", request_type=agent.ListAgentsRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1312,7 +1334,7 @@ def test_list_agents_field_headers():
@pytest.mark.asyncio
async def test_list_agents_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1382,7 +1404,7 @@ def test_list_agents_flattened_error():
@pytest.mark.asyncio
async def test_list_agents_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1411,7 +1433,7 @@ async def test_list_agents_flattened_async():
@pytest.mark.asyncio
async def test_list_agents_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1461,16 +1483,12 @@ def test_list_agents_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_agents(request={}, retry=retry, timeout=timeout)
+ pager = client.list_agents(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1521,7 +1539,7 @@ def test_list_agents_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_agents_async_pager():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1571,7 +1589,7 @@ async def test_list_agents_async_pager():
@pytest.mark.asyncio
async def test_list_agents_async_pages():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1676,6 +1694,25 @@ def test_get_agent(request_type, transport: str = "grpc"):
assert response.locked is True
+def test_get_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetAgentRequest()
+
+
def test_get_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1739,13 +1776,47 @@ def test_get_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_agent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ )
+ )
+ response = await client.get_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetAgentRequest()
+
+
@pytest.mark.asyncio
async def test_get_agent_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1760,23 +1831,27 @@ async def test_get_agent_async_use_cached_wrapped_rpc(transport: str = "grpc_asy
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1784,7 +1859,7 @@ async def test_get_agent_async(
transport: str = "grpc_asyncio", request_type=agent.GetAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1872,7 +1947,7 @@ def test_get_agent_field_headers():
@pytest.mark.asyncio
async def test_get_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1940,7 +2015,7 @@ def test_get_agent_flattened_error():
@pytest.mark.asyncio
async def test_get_agent_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1967,7 +2042,7 @@ async def test_get_agent_flattened_async():
@pytest.mark.asyncio
async def test_get_agent_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2038,6 +2113,25 @@ def test_create_agent(request_type, transport: str = "grpc"):
assert response.locked is True
+def test_create_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_agent.CreateAgentRequest()
+
+
def test_create_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2101,6 +2195,40 @@ def test_create_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_agent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ )
+ )
+ response = await client.create_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_agent.CreateAgentRequest()
+
+
@pytest.mark.asyncio
async def test_create_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2109,7 +2237,7 @@ async def test_create_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2124,23 +2252,27 @@ async def test_create_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2148,7 +2280,7 @@ async def test_create_agent_async(
transport: str = "grpc_asyncio", request_type=gcdc_agent.CreateAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2236,7 +2368,7 @@ def test_create_agent_field_headers():
@pytest.mark.asyncio
async def test_create_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2309,7 +2441,7 @@ def test_create_agent_flattened_error():
@pytest.mark.asyncio
async def test_create_agent_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2340,7 +2472,7 @@ async def test_create_agent_flattened_async():
@pytest.mark.asyncio
async def test_create_agent_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2412,6 +2544,25 @@ def test_update_agent(request_type, transport: str = "grpc"):
assert response.locked is True
+def test_update_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_agent.UpdateAgentRequest()
+
+
def test_update_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2471,6 +2622,40 @@ def test_update_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_agent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ )
+ )
+ response = await client.update_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_agent.UpdateAgentRequest()
+
+
@pytest.mark.asyncio
async def test_update_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2479,7 +2664,7 @@ async def test_update_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2494,23 +2679,27 @@ async def test_update_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2518,7 +2707,7 @@ async def test_update_agent_async(
transport: str = "grpc_asyncio", request_type=gcdc_agent.UpdateAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2606,7 +2795,7 @@ def test_update_agent_field_headers():
@pytest.mark.asyncio
async def test_update_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2679,7 +2868,7 @@ def test_update_agent_flattened_error():
@pytest.mark.asyncio
async def test_update_agent_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2710,7 +2899,7 @@ async def test_update_agent_flattened_async():
@pytest.mark.asyncio
async def test_update_agent_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2756,6 +2945,25 @@ def test_delete_agent(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.DeleteAgentRequest()
+
+
def test_delete_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2819,6 +3027,25 @@ def test_delete_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_agent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.DeleteAgentRequest()
+
+
@pytest.mark.asyncio
async def test_delete_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2827,7 +3054,7 @@ async def test_delete_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2842,23 +3069,27 @@ async def test_delete_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2866,7 +3097,7 @@ async def test_delete_agent_async(
transport: str = "grpc_asyncio", request_type=agent.DeleteAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2927,7 +3158,7 @@ def test_delete_agent_field_headers():
@pytest.mark.asyncio
async def test_delete_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2995,7 +3226,7 @@ def test_delete_agent_flattened_error():
@pytest.mark.asyncio
async def test_delete_agent_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3022,7 +3253,7 @@ async def test_delete_agent_flattened_async():
@pytest.mark.asyncio
async def test_delete_agent_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3067,6 +3298,25 @@ def test_export_agent(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ExportAgentRequest()
+
+
def test_export_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3127,9 +3377,8 @@ def test_export_agent_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_agent(request)
@@ -3139,6 +3388,27 @@ def test_export_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_agent), "__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.export_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ExportAgentRequest()
+
+
@pytest.mark.asyncio
async def test_export_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3147,7 +3417,7 @@ async def test_export_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3162,28 +3432,31 @@ async def test_export_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3191,7 +3464,7 @@ async def test_export_agent_async(
transport: str = "grpc_asyncio", request_type=agent.ExportAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3254,7 +3527,7 @@ def test_export_agent_field_headers():
@pytest.mark.asyncio
async def test_export_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3316,6 +3589,25 @@ def test_restore_agent(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_restore_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.restore_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.restore_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.RestoreAgentRequest()
+
+
def test_restore_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3374,9 +3666,8 @@ def test_restore_agent_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.restore_agent(request)
@@ -3386,6 +3677,27 @@ def test_restore_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_restore_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.restore_agent), "__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.restore_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.RestoreAgentRequest()
+
+
@pytest.mark.asyncio
async def test_restore_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3394,7 +3706,7 @@ async def test_restore_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3409,28 +3721,31 @@ async def test_restore_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.restore_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.restore_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.restore_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3438,7 +3753,7 @@ async def test_restore_agent_async(
transport: str = "grpc_asyncio", request_type=agent.RestoreAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3501,7 +3816,7 @@ def test_restore_agent_field_headers():
@pytest.mark.asyncio
async def test_restore_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3566,6 +3881,25 @@ def test_validate_agent(request_type, transport: str = "grpc"):
assert response.name == "name_value"
+def test_validate_agent_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.validate_agent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.validate_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ValidateAgentRequest()
+
+
def test_validate_agent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3631,6 +3965,29 @@ def test_validate_agent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_validate_agent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.validate_agent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ agent.AgentValidationResult(
+ name="name_value",
+ )
+ )
+ response = await client.validate_agent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.ValidateAgentRequest()
+
+
@pytest.mark.asyncio
async def test_validate_agent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3639,7 +3996,7 @@ async def test_validate_agent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3654,23 +4011,27 @@ async def test_validate_agent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.validate_agent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.validate_agent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.validate_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3678,7 +4039,7 @@ async def test_validate_agent_async(
transport: str = "grpc_asyncio", request_type=agent.ValidateAgentRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3744,7 +4105,7 @@ def test_validate_agent_field_headers():
@pytest.mark.asyncio
async def test_validate_agent_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3811,6 +4172,27 @@ def test_get_agent_validation_result(request_type, transport: str = "grpc"):
assert response.name == "name_value"
+def test_get_agent_validation_result_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_agent_validation_result), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_agent_validation_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetAgentValidationResultRequest()
+
+
def test_get_agent_validation_result_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3883,6 +4265,31 @@ def test_get_agent_validation_result_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_agent_validation_result_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_agent_validation_result), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ agent.AgentValidationResult(
+ name="name_value",
+ )
+ )
+ response = await client.get_agent_validation_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetAgentValidationResultRequest()
+
+
@pytest.mark.asyncio
async def test_get_agent_validation_result_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3891,7 +4298,7 @@ async def test_get_agent_validation_result_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3906,23 +4313,27 @@ async def test_get_agent_validation_result_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_agent_validation_result
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_agent_validation_result(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_agent_validation_result(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3930,7 +4341,7 @@ async def test_get_agent_validation_result_async(
transport: str = "grpc_asyncio", request_type=agent.GetAgentValidationResultRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4000,7 +4411,7 @@ def test_get_agent_validation_result_field_headers():
@pytest.mark.asyncio
async def test_get_agent_validation_result_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4074,7 +4485,7 @@ def test_get_agent_validation_result_flattened_error():
@pytest.mark.asyncio
async def test_get_agent_validation_result_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4105,7 +4516,7 @@ async def test_get_agent_validation_result_flattened_async():
@pytest.mark.asyncio
async def test_get_agent_validation_result_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4157,6 +4568,27 @@ def test_get_generative_settings(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_get_generative_settings_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_generative_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_generative_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetGenerativeSettingsRequest()
+
+
def test_get_generative_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4229,6 +4661,32 @@ def test_get_generative_settings_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_generative_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_generative_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ generative_settings.GenerativeSettings(
+ name="name_value",
+ language_code="language_code_value",
+ )
+ )
+ response = await client.get_generative_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.GetGenerativeSettingsRequest()
+
+
@pytest.mark.asyncio
async def test_get_generative_settings_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4237,7 +4695,7 @@ async def test_get_generative_settings_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4252,23 +4710,27 @@ async def test_get_generative_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_generative_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_generative_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_generative_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4276,7 +4738,7 @@ async def test_get_generative_settings_async(
transport: str = "grpc_asyncio", request_type=agent.GetGenerativeSettingsRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4348,7 +4810,7 @@ def test_get_generative_settings_field_headers():
@pytest.mark.asyncio
async def test_get_generative_settings_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4427,7 +4889,7 @@ def test_get_generative_settings_flattened_error():
@pytest.mark.asyncio
async def test_get_generative_settings_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4462,7 +4924,7 @@ async def test_get_generative_settings_flattened_async():
@pytest.mark.asyncio
async def test_get_generative_settings_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4515,6 +4977,27 @@ def test_update_generative_settings(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_update_generative_settings_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 = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_generative_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_generative_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.UpdateGenerativeSettingsRequest()
+
+
def test_update_generative_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4582,45 +5065,75 @@ def test_update_generative_settings_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_update_generative_settings_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
-):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport=transport,
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+async def test_update_generative_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
- # Ensure method has been cached
- assert (
- client._client._transport.update_generative_settings
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_generative_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_generative_settings.GenerativeSettings(
+ name="name_value",
+ language_code="language_code_value",
+ )
+ )
+ response = await client.update_generative_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == agent.UpdateGenerativeSettingsRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_generative_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_generative_settings
in client._client._transport._wrapped_methods
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_generative_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_generative_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_generative_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4628,7 +5141,7 @@ async def test_update_generative_settings_async(
transport: str = "grpc_asyncio", request_type=agent.UpdateGenerativeSettingsRequest
):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4700,7 +5213,7 @@ def test_update_generative_settings_field_headers():
@pytest.mark.asyncio
async def test_update_generative_settings_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4783,7 +5296,7 @@ def test_update_generative_settings_flattened_error():
@pytest.mark.asyncio
async def test_update_generative_settings_flattened_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4820,7 +5333,7 @@ async def test_update_generative_settings_flattened_async():
@pytest.mark.asyncio
async def test_update_generative_settings_flattened_error_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4835,6 +5348,46 @@ async def test_update_generative_settings_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.ListAgentsRequest,
+ dict,
+ ],
+)
+def test_list_agents_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = agent.ListAgentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = agent.ListAgentsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_agents(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAgentsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_agents_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4967,6 +5520,83 @@ def test_list_agents_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_agents_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
+ )
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_list_agents"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_list_agents"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.ListAgentsRequest.pb(agent.ListAgentsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = agent.ListAgentsResponse.to_json(
+ agent.ListAgentsResponse()
+ )
+
+ request = agent.ListAgentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = agent.ListAgentsResponse()
+
+ client.list_agents(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_agents_rest_bad_request(
+ transport: str = "rest", request_type=agent.ListAgentsRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_agents(request)
+
+
def test_list_agents_rest_flattened():
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5085,6 +5715,69 @@ def test_list_agents_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.GetAgentRequest,
+ dict,
+ ],
+)
+def test_get_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ start_flow="start_flow_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = agent.Agent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_agent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, agent.Agent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_language_code == "default_language_code_value"
+ assert response.supported_language_codes == ["supported_language_codes_value"]
+ assert response.time_zone == "time_zone_value"
+ assert response.description == "description_value"
+ assert response.avatar_uri == "avatar_uri_value"
+ assert response.security_settings == "security_settings_value"
+ assert response.enable_stackdriver_logging is True
+ assert response.enable_spell_correction is True
+ assert response.enable_multi_language_training is True
+ assert response.locked is True
+
+
def test_get_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5202,19 +5895,94 @@ def test_get_agent_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_get_agent_rest_flattened():
- client = AgentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_get_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_get_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.GetAgentRequest.pb(agent.GetAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = agent.Agent()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = agent.Agent.to_json(agent.Agent())
- # get arguments that satisfy an http rule for this method
- sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = agent.GetAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = agent.Agent()
+
+ client.get_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_agent_rest_bad_request(
+ transport: str = "rest", request_type=agent.GetAgentRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_agent(request)
+
+
+def test_get_agent_rest_flattened():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = agent.Agent()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"}
# get truthy value for each flattened field
mock_args = dict(
@@ -5259,6 +6027,195 @@ def test_get_agent_rest_flattened_error(transport: str = "rest"):
)
+def test_get_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_agent.CreateAgentRequest,
+ dict,
+ ],
+)
+def test_create_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init["agent"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "default_language_code": "default_language_code_value",
+ "supported_language_codes": [
+ "supported_language_codes_value1",
+ "supported_language_codes_value2",
+ ],
+ "time_zone": "time_zone_value",
+ "description": "description_value",
+ "avatar_uri": "avatar_uri_value",
+ "speech_to_text_settings": {"enable_speech_adaptation": True},
+ "start_flow": "start_flow_value",
+ "start_playbook": "start_playbook_value",
+ "security_settings": "security_settings_value",
+ "enable_stackdriver_logging": True,
+ "enable_spell_correction": True,
+ "enable_multi_language_training": True,
+ "locked": True,
+ "advanced_settings": {
+ "audio_export_gcs_destination": {"uri": "uri_value"},
+ "speech_settings": {
+ "endpointer_sensitivity": 2402,
+ "no_speech_timeout": {"seconds": 751, "nanos": 543},
+ "use_timeout_based_endpointing": True,
+ "models": {},
+ },
+ "dtmf_settings": {
+ "enabled": True,
+ "max_digits": 1065,
+ "finish_digit": "finish_digit_value",
+ "interdigit_timeout_duration": {},
+ "endpointing_timeout_duration": {},
+ },
+ "logging_settings": {
+ "enable_stackdriver_logging": True,
+ "enable_interaction_logging": True,
+ },
+ },
+ "git_integration_settings": {
+ "github_settings": {
+ "display_name": "display_name_value",
+ "repository_uri": "repository_uri_value",
+ "tracking_branch": "tracking_branch_value",
+ "access_token": "access_token_value",
+ "branches": ["branches_value1", "branches_value2"],
+ }
+ },
+ "text_to_speech_settings": {"synthesize_speech_configs": {}},
+ "gen_app_builder_settings": {"engine": "engine_value"},
+ "answer_feedback_settings": {"enable_answer_feedback": True},
+ "personalization_settings": {"default_end_user_metadata": {"fields": {}}},
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_agent.CreateAgentRequest.meta.fields["agent"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["agent"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["agent"][field])):
+ del request_init["agent"][field][i][subfield]
+ else:
+ del request_init["agent"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ start_flow="start_flow_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_agent.Agent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_agent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_agent.Agent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_language_code == "default_language_code_value"
+ assert response.supported_language_codes == ["supported_language_codes_value"]
+ assert response.time_zone == "time_zone_value"
+ assert response.description == "description_value"
+ assert response.avatar_uri == "avatar_uri_value"
+ assert response.security_settings == "security_settings_value"
+ assert response.enable_stackdriver_logging is True
+ assert response.enable_spell_correction is True
+ assert response.enable_multi_language_training is True
+ assert response.locked is True
+
+
def test_create_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5385,181 +6342,82 @@ def test_create_agent_rest_unset_required_fields():
)
-def test_create_agent_rest_flattened():
- client = AgentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_create_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_create_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_agent.CreateAgentRequest.pb(gcdc_agent.CreateAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_agent.Agent()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- agent=gcdc_agent.Agent(name="name_value"),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_agent.Agent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.create_agent(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*}/agents"
- % client.transport._host,
- args[1],
- )
-
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_agent.Agent.to_json(gcdc_agent.Agent())
-def test_create_agent_rest_flattened_error(transport: str = "rest"):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ request = gcdc_agent.CreateAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_agent.Agent()
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
client.create_agent(
- gcdc_agent.CreateAgentRequest(),
- parent="parent_value",
- agent=gcdc_agent.Agent(name="name_value"),
- )
-
-
-def test_update_agent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_agent in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[client._transport.update_agent] = mock_rpc
-
- request = {}
- client.update_agent(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.update_agent(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_update_agent_rest_required_fields(request_type=gcdc_agent.UpdateAgentRequest):
- transport_class = transports.AgentsRestTransport
-
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_agent._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_agent._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
- jsonified_request.update(unset_fields)
+ pre.assert_called_once()
+ post.assert_called_once()
- # verify required fields with non-default values are left alone
+def test_create_agent_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_agent.CreateAgentRequest
+):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_agent.Agent()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "patch",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_agent.Agent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.update_agent(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_agent_rest_unset_required_fields():
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
- unset_fields = transport.update_agent._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("agent",)))
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_agent(request)
-def test_update_agent_rest_flattened():
+def test_create_agent_rest_flattened():
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -5571,14 +6429,12 @@ def test_update_agent_rest_flattened():
return_value = gcdc_agent.Agent()
# get arguments that satisfy an http rule for this method
- sample_request = {
- "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
- }
+ sample_request = {"parent": "projects/sample1/locations/sample2"}
# get truthy value for each flattened field
mock_args = dict(
+ parent="parent_value",
agent=gcdc_agent.Agent(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
@@ -5591,20 +6447,20 @@ def test_update_agent_rest_flattened():
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.update_agent(**mock_args)
+ client.create_agent(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{agent.name=projects/*/locations/*/agents/*}"
+ "%s/v3beta1/{parent=projects/*/locations/*}/agents"
% client.transport._host,
args[1],
)
-def test_update_agent_rest_flattened_error(transport: str = "rest"):
+def test_create_agent_rest_flattened_error(transport: str = "rest"):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5613,54 +6469,244 @@ def test_update_agent_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.update_agent(
- gcdc_agent.UpdateAgentRequest(),
+ client.create_agent(
+ gcdc_agent.CreateAgentRequest(),
+ parent="parent_value",
agent=gcdc_agent.Agent(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_delete_agent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.delete_agent in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.delete_agent] = mock_rpc
-
- request = {}
- client.delete_agent(request)
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
- client.delete_agent(request)
+def test_create_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_agent.UpdateAgentRequest,
+ dict,
+ ],
+)
+def test_update_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
-def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest):
+ # send a request that will satisfy transcoding
+ request_init = {
+ "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ }
+ request_init["agent"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3",
+ "display_name": "display_name_value",
+ "default_language_code": "default_language_code_value",
+ "supported_language_codes": [
+ "supported_language_codes_value1",
+ "supported_language_codes_value2",
+ ],
+ "time_zone": "time_zone_value",
+ "description": "description_value",
+ "avatar_uri": "avatar_uri_value",
+ "speech_to_text_settings": {"enable_speech_adaptation": True},
+ "start_flow": "start_flow_value",
+ "start_playbook": "start_playbook_value",
+ "security_settings": "security_settings_value",
+ "enable_stackdriver_logging": True,
+ "enable_spell_correction": True,
+ "enable_multi_language_training": True,
+ "locked": True,
+ "advanced_settings": {
+ "audio_export_gcs_destination": {"uri": "uri_value"},
+ "speech_settings": {
+ "endpointer_sensitivity": 2402,
+ "no_speech_timeout": {"seconds": 751, "nanos": 543},
+ "use_timeout_based_endpointing": True,
+ "models": {},
+ },
+ "dtmf_settings": {
+ "enabled": True,
+ "max_digits": 1065,
+ "finish_digit": "finish_digit_value",
+ "interdigit_timeout_duration": {},
+ "endpointing_timeout_duration": {},
+ },
+ "logging_settings": {
+ "enable_stackdriver_logging": True,
+ "enable_interaction_logging": True,
+ },
+ },
+ "git_integration_settings": {
+ "github_settings": {
+ "display_name": "display_name_value",
+ "repository_uri": "repository_uri_value",
+ "tracking_branch": "tracking_branch_value",
+ "access_token": "access_token_value",
+ "branches": ["branches_value1", "branches_value2"],
+ }
+ },
+ "text_to_speech_settings": {"synthesize_speech_configs": {}},
+ "gen_app_builder_settings": {"engine": "engine_value"},
+ "answer_feedback_settings": {"enable_answer_feedback": True},
+ "personalization_settings": {"default_end_user_metadata": {"fields": {}}},
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_agent.UpdateAgentRequest.meta.fields["agent"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["agent"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["agent"][field])):
+ del request_init["agent"][field][i][subfield]
+ else:
+ del request_init["agent"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_agent.Agent(
+ name="name_value",
+ display_name="display_name_value",
+ default_language_code="default_language_code_value",
+ supported_language_codes=["supported_language_codes_value"],
+ time_zone="time_zone_value",
+ description="description_value",
+ avatar_uri="avatar_uri_value",
+ security_settings="security_settings_value",
+ enable_stackdriver_logging=True,
+ enable_spell_correction=True,
+ enable_multi_language_training=True,
+ locked=True,
+ start_flow="start_flow_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_agent.Agent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_agent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_agent.Agent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_language_code == "default_language_code_value"
+ assert response.supported_language_codes == ["supported_language_codes_value"]
+ assert response.time_zone == "time_zone_value"
+ assert response.description == "description_value"
+ assert response.avatar_uri == "avatar_uri_value"
+ assert response.security_settings == "security_settings_value"
+ assert response.enable_stackdriver_logging is True
+ assert response.enable_spell_correction is True
+ assert response.enable_multi_language_training is True
+ assert response.locked is True
+
+
+def test_update_agent_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_agent in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_agent] = mock_rpc
+
+ request = {}
+ client.update_agent(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_agent(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_agent_rest_required_fields(request_type=gcdc_agent.UpdateAgentRequest):
transport_class = transports.AgentsRestTransport
request_init = {}
- request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5671,21 +6717,19 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_agent._get_unset_required_fields(jsonified_request)
+ ).update_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
-
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_agent._get_unset_required_fields(jsonified_request)
+ ).update_agent._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("update_mask",))
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5694,7 +6738,7 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = gcdc_agent.Agent()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -5706,75 +6750,161 @@ def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "delete",
+ "method": "patch",
"query_params": pb_request,
}
+ transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+
+ # Convert return value to protobuf type
+ return_value = gcdc_agent.Agent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_agent(request)
+ response = client.update_agent(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_delete_agent_rest_unset_required_fields():
+def test_update_agent_rest_unset_required_fields():
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.delete_agent._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ unset_fields = transport.update_agent._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("updateMask",)) & set(("agent",)))
-def test_delete_agent_rest_flattened():
- client = AgentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"}
-
- # get truthy value for each flattened field
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_update_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_update_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_agent.UpdateAgentRequest.pb(gcdc_agent.UpdateAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_agent.Agent.to_json(gcdc_agent.Agent())
+
+ request = gcdc_agent.UpdateAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_agent.Agent()
+
+ client.update_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_agent_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_agent.UpdateAgentRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_agent(request)
+
+
+def test_update_agent_rest_flattened():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_agent.Agent()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ }
+
+ # get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ agent=gcdc_agent.Agent(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+ # Convert return value to protobuf type
+ return_value = gcdc_agent.Agent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.delete_agent(**mock_args)
+ client.update_agent(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*}"
+ "%s/v3beta1/{agent.name=projects/*/locations/*/agents/*}"
% client.transport._host,
args[1],
)
-def test_delete_agent_rest_flattened_error(transport: str = "rest"):
+def test_update_agent_rest_flattened_error(transport: str = "rest"):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5783,13 +6913,55 @@ def test_delete_agent_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.delete_agent(
- agent.DeleteAgentRequest(),
- name="name_value",
+ client.update_agent(
+ gcdc_agent.UpdateAgentRequest(),
+ agent=gcdc_agent.Agent(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
-def test_export_agent_rest_use_cached_wrapped_rpc():
+def test_update_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.DeleteAgentRequest,
+ dict,
+ ],
+)
+def test_delete_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_agent(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -5803,33 +6975,29 @@ def test_export_agent_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.export_agent in client._transport._wrapped_methods
+ assert client._transport.delete_agent in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.export_agent] = mock_rpc
+ client._transport._wrapped_methods[client._transport.delete_agent] = mock_rpc
request = {}
- client.export_agent(request)
+ client.delete_agent(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.export_agent(request)
+ client.delete_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest):
+def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest):
transport_class = transports.AgentsRestTransport
request_init = {}
@@ -5844,7 +7012,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).export_agent._get_unset_required_fields(jsonified_request)
+ ).delete_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
@@ -5853,7 +7021,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).export_agent._get_unset_required_fields(jsonified_request)
+ ).delete_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
@@ -5867,7 +7035,7 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -5879,155 +7047,200 @@ def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "post",
+ "method": "delete",
"query_params": pb_request,
}
- transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
+ json_return_value = ""
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.export_agent(request)
+ response = client.delete_agent(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_export_agent_rest_unset_required_fields():
+def test_delete_agent_rest_unset_required_fields():
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.export_agent._get_unset_required_fields({})
+ unset_fields = transport.delete_agent._get_unset_required_fields({})
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_restore_agent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
+ )
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_delete_agent"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- # Ensure method has been cached
- assert client._transport.restore_agent in client._transport._wrapped_methods
+ request = agent.DeleteAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.delete_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[client._transport.restore_agent] = mock_rpc
-
- request = {}
- client.restore_agent(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.restore_agent(request)
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
-def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest):
- transport_class = transports.AgentsRestTransport
+def test_delete_agent_rest_bad_request(
+ transport: str = "rest", request_type=agent.DeleteAgentRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- request_init = {}
- request_init["name"] = ""
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_agent(request)
+
+
+def test_delete_agent_rest_flattened():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # verify fields with default values are dropped
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).restore_agent._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- # verify required fields with default values are now present
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
- jsonified_request["name"] = "name_value"
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).restore_agent._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
+ client.delete_agent(**mock_args)
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+def test_delete_agent_rest_flattened_error(transport: str = "rest"):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_agent(
+ agent.DeleteAgentRequest(),
+ name="name_value",
+ )
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+def test_delete_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- response = client.restore_agent(request)
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.ExportAgentRequest,
+ dict,
+ ],
+)
+def test_export_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
-def test_restore_agent_rest_unset_required_fields():
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
- unset_fields = transport.restore_agent._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.export_agent(request)
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
-def test_validate_agent_rest_use_cached_wrapped_rpc():
+
+def test_export_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -6041,29 +7254,33 @@ def test_validate_agent_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.validate_agent in client._transport._wrapped_methods
+ assert client._transport.export_agent in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.validate_agent] = mock_rpc
+ client._transport._wrapped_methods[client._transport.export_agent] = mock_rpc
request = {}
- client.validate_agent(request)
+ client.export_agent(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.validate_agent(request)
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.export_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentRequest):
+def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest):
transport_class = transports.AgentsRestTransport
request_init = {}
@@ -6078,7 +7295,7 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).validate_agent._get_unset_required_fields(jsonified_request)
+ ).export_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
@@ -6087,7 +7304,7 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).validate_agent._get_unset_required_fields(jsonified_request)
+ ).export_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
@@ -6101,7 +7318,7 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = agent.AgentValidationResult()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6121,216 +7338,148 @@ def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentReq
response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = agent.AgentValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.validate_agent(request)
+ response = client.export_agent(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_validate_agent_rest_unset_required_fields():
+def test_export_agent_rest_unset_required_fields():
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.validate_agent._get_unset_required_fields({})
+ unset_fields = transport.export_agent._get_unset_required_fields({})
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_get_agent_validation_result_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.get_agent_validation_result
- in client._transport._wrapped_methods
- )
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
+ )
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.AgentsRestInterceptor, "post_export_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_export_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- client._transport._wrapped_methods[
- client._transport.get_agent_validation_result
- ] = mock_rpc
-
- request = {}
- client.get_agent_validation_result(request)
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ request = agent.ExportAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- client.get_agent_validation_result(request)
+ client.export_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_get_agent_validation_result_rest_required_fields(
- request_type=agent.GetAgentValidationResultRequest,
+def test_export_agent_rest_bad_request(
+ transport: str = "rest", request_type=agent.ExportAgentRequest
):
- transport_class = transports.AgentsRestTransport
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_agent_validation_result._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_agent_validation_result._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
- # Designate an appropriate value for the returned response.
- return_value = agent.AgentValidationResult()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = agent.AgentValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.get_agent_validation_result(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.export_agent(request)
-def test_get_agent_validation_result_rest_unset_required_fields():
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
+def test_export_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- unset_fields = transport.get_agent_validation_result._get_unset_required_fields({})
- assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
-
-def test_get_agent_validation_result_rest_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.RestoreAgentRequest,
+ dict,
+ ],
+)
+def test_restore_agent_rest(request_type):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = agent.AgentValidationResult()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = agent.AgentValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
+
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
+ response = client.restore_agent(request)
- client.get_agent_validation_result(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/validationResult}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_agent_validation_result_rest_flattened_error(transport: str = "rest"):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_agent_validation_result(
- agent.GetAgentValidationResultRequest(),
- name="name_value",
- )
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
-def test_get_generative_settings_rest_use_cached_wrapped_rpc():
+def test_restore_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -6344,41 +7493,37 @@ def test_get_generative_settings_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert (
- client._transport.get_generative_settings
- in client._transport._wrapped_methods
- )
+ assert client._transport.restore_agent in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[
- client._transport.get_generative_settings
- ] = mock_rpc
+ client._transport._wrapped_methods[client._transport.restore_agent] = mock_rpc
request = {}
- client.get_generative_settings(request)
+ client.restore_agent(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.get_generative_settings(request)
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.restore_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_get_generative_settings_rest_required_fields(
- request_type=agent.GetGenerativeSettingsRequest,
-):
+def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest):
transport_class = transports.AgentsRestTransport
request_init = {}
request_init["name"] = ""
- request_init["language_code"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -6386,32 +7531,24 @@ def test_get_generative_settings_rest_required_fields(
)
# verify fields with default values are dropped
- assert "languageCode" not in jsonified_request
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).get_generative_settings._get_unset_required_fields(jsonified_request)
+ ).restore_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- assert "languageCode" in jsonified_request
- assert jsonified_request["languageCode"] == request_init["language_code"]
jsonified_request["name"] = "name_value"
- jsonified_request["languageCode"] = "language_code_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).get_generative_settings._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
+ ).restore_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
assert "name" in jsonified_request
assert jsonified_request["name"] == "name_value"
- assert "languageCode" in jsonified_request
- assert jsonified_request["languageCode"] == "language_code_value"
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6420,7 +7557,7 @@ def test_get_generative_settings_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = generative_settings.GenerativeSettings()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6432,113 +7569,161 @@ def test_get_generative_settings_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "get",
+ "method": "post",
"query_params": pb_request,
}
+ transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = generative_settings.GenerativeSettings.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_generative_settings(request)
+ response = client.restore_agent(request)
- expected_params = [
- (
- "languageCode",
- "",
- ),
- ("$alt", "json;enum-encoding=int"),
- ]
+ expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_get_generative_settings_rest_unset_required_fields():
+def test_restore_agent_rest_unset_required_fields():
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.get_generative_settings._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("languageCode",))
- & set(
- (
- "name",
- "languageCode",
- )
- )
- )
+ unset_fields = transport.restore_agent._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-def test_get_generative_settings_rest_flattened():
- client = AgentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_restore_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = generative_settings.GenerativeSettings()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.AgentsRestInterceptor, "post_restore_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_restore_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- language_code="language_code_value",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = generative_settings.GenerativeSettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.get_generative_settings(**mock_args)
+ request = agent.RestoreAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/generativeSettings}"
- % client.transport._host,
- args[1],
+ client.restore_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
+ pre.assert_called_once()
+ post.assert_called_once()
+
-def test_get_generative_settings_rest_flattened_error(transport: str = "rest"):
+def test_restore_agent_rest_bad_request(
+ transport: str = "rest", request_type=agent.RestoreAgentRequest
+):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_generative_settings(
- agent.GetGenerativeSettingsRequest(),
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.restore_agent(request)
+
+
+def test_restore_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ agent.ValidateAgentRequest,
+ dict,
+ ],
+)
+def test_validate_agent_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = agent.AgentValidationResult(
name="name_value",
- language_code="language_code_value",
)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = agent.AgentValidationResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.validate_agent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, agent.AgentValidationResult)
+ assert response.name == "name_value"
+
-def test_update_generative_settings_rest_use_cached_wrapped_rpc():
+def test_validate_agent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -6552,39 +7737,33 @@ def test_update_generative_settings_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert (
- client._transport.update_generative_settings
- in client._transport._wrapped_methods
- )
+ assert client._transport.validate_agent in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[
- client._transport.update_generative_settings
- ] = mock_rpc
+ client._transport._wrapped_methods[client._transport.validate_agent] = mock_rpc
request = {}
- client.update_generative_settings(request)
+ client.validate_agent(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_generative_settings(request)
+ client.validate_agent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_update_generative_settings_rest_required_fields(
- request_type=agent.UpdateGenerativeSettingsRequest,
-):
+def test_validate_agent_rest_required_fields(request_type=agent.ValidateAgentRequest):
transport_class = transports.AgentsRestTransport
request_init = {}
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -6595,19 +7774,21 @@ def test_update_generative_settings_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_generative_settings._get_unset_required_fields(jsonified_request)
+ ).validate_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ jsonified_request["name"] = "name_value"
+
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_generative_settings._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
+ ).validate_agent._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6616,7 +7797,7 @@ def test_update_generative_settings_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = gcdc_generative_settings.GenerativeSettings()
+ return_value = agent.AgentValidationResult()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6628,7 +7809,7 @@ def test_update_generative_settings_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "patch",
+ "method": "post",
"query_params": pb_request,
}
transcode_result["body"] = pb_request
@@ -6638,1733 +7819,300 @@ def test_update_generative_settings_rest_required_fields(
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
+ return_value = agent.AgentValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.update_generative_settings(request)
+ response = client.validate_agent(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_update_generative_settings_rest_unset_required_fields():
+def test_validate_agent_rest_unset_required_fields():
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.update_generative_settings._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("generativeSettings",)))
+ unset_fields = transport.validate_agent._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-def test_update_generative_settings_rest_flattened():
- client = AgentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_validate_agent_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_generative_settings.GenerativeSettings()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "generative_settings": {
- "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
- }
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_validate_agent"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_validate_agent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.ValidateAgentRequest.pb(agent.ValidateAgentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- generative_settings=gcdc_generative_settings.GenerativeSettings(
- name="name_value"
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = agent.AgentValidationResult.to_json(
+ agent.AgentValidationResult()
)
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- client.update_generative_settings(**mock_args)
+ request = agent.ValidateAgentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = agent.AgentValidationResult()
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{generative_settings.name=projects/*/locations/*/agents/*/generativeSettings}"
- % client.transport._host,
- args[1],
+ client.validate_agent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_update_generative_settings_rest_flattened_error(transport: str = "rest"):
+
+def test_validate_agent_rest_bad_request(
+ transport: str = "rest", request_type=agent.ValidateAgentRequest
+):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_generative_settings(
- agent.UpdateGenerativeSettingsRequest(),
- generative_settings=gcdc_generative_settings.GenerativeSettings(
- name="name_value"
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.validate_agent(request)
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+def test_validate_agent_rest_error():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- with pytest.raises(ValueError):
- client = AgentsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = AgentsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = AgentsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = AgentsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = AgentsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.AgentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.AgentsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.AgentsGrpcTransport,
- transports.AgentsGrpcAsyncIOTransport,
- transports.AgentsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = AgentsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_agents_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_agents), "__call__") as call:
- call.return_value = agent.ListAgentsResponse()
- client.list_agents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ListAgentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_agent), "__call__") as call:
- call.return_value = agent.Agent()
- client.get_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_agent), "__call__") as call:
- call.return_value = gcdc_agent.Agent()
- client.create_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.CreateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_agent), "__call__") as call:
- call.return_value = gcdc_agent.Agent()
- client.update_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.UpdateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_agent), "__call__") as call:
- call.return_value = None
- client.delete_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.DeleteAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_agent), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ExportAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_restore_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.restore_agent), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.restore_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.RestoreAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_validate_agent_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_agent), "__call__") as call:
- call.return_value = agent.AgentValidationResult()
- client.validate_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ValidateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_agent_validation_result_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_agent_validation_result), "__call__"
- ) as call:
- call.return_value = agent.AgentValidationResult()
- client.get_agent_validation_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentValidationResultRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_generative_settings_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_generative_settings), "__call__"
- ) as call:
- call.return_value = generative_settings.GenerativeSettings()
- client.get_generative_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetGenerativeSettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_generative_settings_empty_call_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_generative_settings), "__call__"
- ) as call:
- call.return_value = gcdc_generative_settings.GenerativeSettings()
- client.update_generative_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.UpdateGenerativeSettingsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = AgentsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_agents_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_agents), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- agent.ListAgentsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_agents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ListAgentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- )
- )
- await client.get_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- )
- )
- await client.create_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.CreateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- )
- )
- await client.update_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.UpdateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.DeleteAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.export_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ExportAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_restore_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.restore_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.restore_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.RestoreAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_validate_agent_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_agent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- agent.AgentValidationResult(
- name="name_value",
- )
- )
- await client.validate_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ValidateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_agent_validation_result_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_agent_validation_result), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- agent.AgentValidationResult(
- name="name_value",
- )
- )
- await client.get_agent_validation_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentValidationResultRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_generative_settings_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_generative_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- generative_settings.GenerativeSettings(
- name="name_value",
- language_code="language_code_value",
- )
- )
- await client.get_generative_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetGenerativeSettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_generative_settings_empty_call_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_generative_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_generative_settings.GenerativeSettings(
- name="name_value",
- language_code="language_code_value",
- )
- )
- await client.update_generative_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.UpdateGenerativeSettingsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = AgentsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_agents_rest_bad_request(request_type=agent.ListAgentsRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_agents(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.ListAgentsRequest,
- dict,
- ],
-)
-def test_list_agents_rest_call_success(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = agent.ListAgentsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = agent.ListAgentsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_agents(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListAgentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_agents_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_list_agents"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_list_agents"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.ListAgentsRequest.pb(agent.ListAgentsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = agent.ListAgentsResponse.to_json(agent.ListAgentsResponse())
- req.return_value.content = return_value
-
- request = agent.ListAgentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = agent.ListAgentsResponse()
-
- client.list_agents(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_agent_rest_bad_request(request_type=agent.GetAgentRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_agent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.GetAgentRequest,
- dict,
- ],
-)
-def test_get_agent_rest_call_success(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- start_flow="start_flow_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = agent.Agent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_agent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, agent.Agent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.default_language_code == "default_language_code_value"
- assert response.supported_language_codes == ["supported_language_codes_value"]
- assert response.time_zone == "time_zone_value"
- assert response.description == "description_value"
- assert response.avatar_uri == "avatar_uri_value"
- assert response.security_settings == "security_settings_value"
- assert response.enable_stackdriver_logging is True
- assert response.enable_spell_correction is True
- assert response.enable_multi_language_training is True
- assert response.locked is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_get_agent"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_get_agent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.GetAgentRequest.pb(agent.GetAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = agent.Agent.to_json(agent.Agent())
- req.return_value.content = return_value
-
- request = agent.GetAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = agent.Agent()
-
- client.get_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_agent_rest_bad_request(request_type=gcdc_agent.CreateAgentRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_agent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_agent.CreateAgentRequest,
- dict,
- ],
-)
-def test_create_agent_rest_call_success(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["agent"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "default_language_code": "default_language_code_value",
- "supported_language_codes": [
- "supported_language_codes_value1",
- "supported_language_codes_value2",
- ],
- "time_zone": "time_zone_value",
- "description": "description_value",
- "avatar_uri": "avatar_uri_value",
- "speech_to_text_settings": {"enable_speech_adaptation": True},
- "start_flow": "start_flow_value",
- "start_playbook": "start_playbook_value",
- "security_settings": "security_settings_value",
- "enable_stackdriver_logging": True,
- "enable_spell_correction": True,
- "enable_multi_language_training": True,
- "locked": True,
- "advanced_settings": {
- "audio_export_gcs_destination": {"uri": "uri_value"},
- "speech_settings": {
- "endpointer_sensitivity": 2402,
- "no_speech_timeout": {"seconds": 751, "nanos": 543},
- "use_timeout_based_endpointing": True,
- "models": {},
- },
- "dtmf_settings": {
- "enabled": True,
- "max_digits": 1065,
- "finish_digit": "finish_digit_value",
- "interdigit_timeout_duration": {},
- "endpointing_timeout_duration": {},
- },
- "logging_settings": {
- "enable_stackdriver_logging": True,
- "enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
- },
- },
- "git_integration_settings": {
- "github_settings": {
- "display_name": "display_name_value",
- "repository_uri": "repository_uri_value",
- "tracking_branch": "tracking_branch_value",
- "access_token": "access_token_value",
- "branches": ["branches_value1", "branches_value2"],
- }
- },
- "text_to_speech_settings": {"synthesize_speech_configs": {}},
- "gen_app_builder_settings": {"engine": "engine_value"},
- "answer_feedback_settings": {"enable_answer_feedback": True},
- "personalization_settings": {"default_end_user_metadata": {"fields": {}}},
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_agent.CreateAgentRequest.meta.fields["agent"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["agent"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["agent"][field])):
- del request_init["agent"][field][i][subfield]
- else:
- del request_init["agent"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- start_flow="start_flow_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_agent.Agent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_agent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_agent.Agent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.default_language_code == "default_language_code_value"
- assert response.supported_language_codes == ["supported_language_codes_value"]
- assert response.time_zone == "time_zone_value"
- assert response.description == "description_value"
- assert response.avatar_uri == "avatar_uri_value"
- assert response.security_settings == "security_settings_value"
- assert response.enable_stackdriver_logging is True
- assert response.enable_spell_correction is True
- assert response.enable_multi_language_training is True
- assert response.locked is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_create_agent"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_create_agent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_agent.CreateAgentRequest.pb(gcdc_agent.CreateAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_agent.Agent.to_json(gcdc_agent.Agent())
- req.return_value.content = return_value
-
- request = gcdc_agent.CreateAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_agent.Agent()
-
- client.create_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_agent_rest_bad_request(request_type=gcdc_agent.UpdateAgentRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_agent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_agent.UpdateAgentRequest,
- dict,
- ],
-)
-def test_update_agent_rest_call_success(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "agent": {"name": "projects/sample1/locations/sample2/agents/sample3"}
- }
- request_init["agent"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3",
- "display_name": "display_name_value",
- "default_language_code": "default_language_code_value",
- "supported_language_codes": [
- "supported_language_codes_value1",
- "supported_language_codes_value2",
- ],
- "time_zone": "time_zone_value",
- "description": "description_value",
- "avatar_uri": "avatar_uri_value",
- "speech_to_text_settings": {"enable_speech_adaptation": True},
- "start_flow": "start_flow_value",
- "start_playbook": "start_playbook_value",
- "security_settings": "security_settings_value",
- "enable_stackdriver_logging": True,
- "enable_spell_correction": True,
- "enable_multi_language_training": True,
- "locked": True,
- "advanced_settings": {
- "audio_export_gcs_destination": {"uri": "uri_value"},
- "speech_settings": {
- "endpointer_sensitivity": 2402,
- "no_speech_timeout": {"seconds": 751, "nanos": 543},
- "use_timeout_based_endpointing": True,
- "models": {},
- },
- "dtmf_settings": {
- "enabled": True,
- "max_digits": 1065,
- "finish_digit": "finish_digit_value",
- "interdigit_timeout_duration": {},
- "endpointing_timeout_duration": {},
- },
- "logging_settings": {
- "enable_stackdriver_logging": True,
- "enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
- },
- },
- "git_integration_settings": {
- "github_settings": {
- "display_name": "display_name_value",
- "repository_uri": "repository_uri_value",
- "tracking_branch": "tracking_branch_value",
- "access_token": "access_token_value",
- "branches": ["branches_value1", "branches_value2"],
- }
- },
- "text_to_speech_settings": {"synthesize_speech_configs": {}},
- "gen_app_builder_settings": {"engine": "engine_value"},
- "answer_feedback_settings": {"enable_answer_feedback": True},
- "personalization_settings": {"default_end_user_metadata": {"fields": {}}},
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_agent.UpdateAgentRequest.meta.fields["agent"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["agent"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["agent"][field])):
- del request_init["agent"][field][i][subfield]
- else:
- del request_init["agent"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_agent.Agent(
- name="name_value",
- display_name="display_name_value",
- default_language_code="default_language_code_value",
- supported_language_codes=["supported_language_codes_value"],
- time_zone="time_zone_value",
- description="description_value",
- avatar_uri="avatar_uri_value",
- security_settings="security_settings_value",
- enable_stackdriver_logging=True,
- enable_spell_correction=True,
- enable_multi_language_training=True,
- locked=True,
- start_flow="start_flow_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_agent.Agent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_agent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_agent.Agent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.default_language_code == "default_language_code_value"
- assert response.supported_language_codes == ["supported_language_codes_value"]
- assert response.time_zone == "time_zone_value"
- assert response.description == "description_value"
- assert response.avatar_uri == "avatar_uri_value"
- assert response.security_settings == "security_settings_value"
- assert response.enable_stackdriver_logging is True
- assert response.enable_spell_correction is True
- assert response.enable_multi_language_training is True
- assert response.locked is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_update_agent"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_update_agent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_agent.UpdateAgentRequest.pb(gcdc_agent.UpdateAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_agent.Agent.to_json(gcdc_agent.Agent())
- req.return_value.content = return_value
-
- request = gcdc_agent.UpdateAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_agent.Agent()
-
- client.update_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_agent_rest_bad_request(request_type=agent.DeleteAgentRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_agent(request)
@pytest.mark.parametrize(
"request_type",
[
- agent.DeleteAgentRequest,
+ agent.GetAgentValidationResultRequest,
dict,
],
)
-def test_delete_agent_rest_call_success(request_type):
+def test_get_agent_validation_result_rest(request_type):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = agent.AgentValidationResult(
+ name="name_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = agent.AgentValidationResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_agent(request)
+ response = client.get_agent_validation_result(request)
# Establish that the response is the type that we expect.
- assert response is None
-
+ assert isinstance(response, agent.AgentValidationResult)
+ assert response.name == "name_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_delete_agent"
- ) as pre:
- pre.assert_not_called()
- pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+def test_get_agent_validation_result_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = agent.DeleteAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
+ # Ensure method has been cached
+ assert (
+ client._transport.get_agent_validation_result
+ in client._transport._wrapped_methods
+ )
- client.delete_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[
+ client._transport.get_agent_validation_result
+ ] = mock_rpc
- pre.assert_called_once()
+ request = {}
+ client.get_agent_validation_result(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+ client.get_agent_validation_result(request)
-def test_export_agent_rest_bad_request(request_type=agent.ExportAgentRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_get_agent_validation_result_rest_required_fields(
+ request_type=agent.GetAgentValidationResultRequest,
+):
+ transport_class = transports.AgentsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_agent(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_agent_validation_result._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_agent_validation_result._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.ExportAgentRequest,
- dict,
- ],
-)
-def test_export_agent_rest_call_success(request_type):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
-
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
+ # Designate an appropriate value for the returned response.
+ return_value = agent.AgentValidationResult()
# Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_agent(request)
+ response_value = Response()
+ response_value.status_code = 200
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ # Convert return value to protobuf type
+ return_value = agent.AgentValidationResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_agent_validation_result(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_get_agent_validation_result_rest_unset_required_fields():
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.get_agent_validation_result._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_agent_rest_interceptors(null_interceptor):
+def test_get_agent_validation_result_rest_interceptors(null_interceptor):
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
client = AgentsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.AgentsRestInterceptor, "post_export_agent"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_get_agent_validation_result"
) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_export_agent"
+ transports.AgentsRestInterceptor, "pre_get_agent_validation_result"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest())
+ pb_message = agent.GetAgentValidationResultRequest.pb(
+ agent.GetAgentValidationResultRequest()
+ )
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -8372,20 +8120,22 @@ def test_export_agent_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = agent.AgentValidationResult.to_json(
+ agent.AgentValidationResult()
+ )
- request = agent.ExportAgentRequest()
+ request = agent.GetAgentValidationResultRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ post.return_value = agent.AgentValidationResult()
- client.export_agent(
+ client.get_agent_validation_result(
request,
metadata=[
("key", "val"),
@@ -8397,12 +8147,18 @@ def test_export_agent_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_restore_agent_rest_bad_request(request_type=agent.RestoreAgentRequest):
+def test_get_agent_validation_result_rest_bad_request(
+ transport: str = "rest", request_type=agent.GetAgentValidationResultRequest
+):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -8410,305 +8166,289 @@ def test_restore_agent_rest_bad_request(request_type=agent.RestoreAgentRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.restore_agent(request)
+ client.get_agent_validation_result(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.RestoreAgentRequest,
- dict,
- ],
-)
-def test_restore_agent_rest_call_success(request_type):
+def test_get_agent_validation_result_rest_flattened():
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = agent.AgentValidationResult()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = agent.AgentValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.restore_agent(request)
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ client.get_agent_validation_result(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/validationResult}"
+ % client.transport._host,
+ args[1],
+ )
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_restore_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
+def test_get_agent_validation_result_rest_flattened_error(transport: str = "rest"):
+ client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
+ transport=transport,
)
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.AgentsRestInterceptor, "post_restore_agent"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_restore_agent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = agent.RestoreAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
- client.restore_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_agent_validation_result(
+ agent.GetAgentValidationResultRequest(),
+ name="name_value",
)
- pre.assert_called_once()
- post.assert_called_once()
-
-def test_validate_agent_rest_bad_request(request_type=agent.ValidateAgentRequest):
+def test_get_agent_validation_result_rest_error():
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.validate_agent(request)
@pytest.mark.parametrize(
"request_type",
[
- agent.ValidateAgentRequest,
+ agent.GetGenerativeSettingsRequest,
dict,
],
)
-def test_validate_agent_rest_call_success(request_type):
+def test_get_generative_settings_rest(request_type):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = agent.AgentValidationResult(
+ return_value = generative_settings.GenerativeSettings(
name="name_value",
+ language_code="language_code_value",
)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
- return_value = agent.AgentValidationResult.pb(return_value)
+ return_value = generative_settings.GenerativeSettings.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.validate_agent(request)
+ response = client.get_generative_settings(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, agent.AgentValidationResult)
+ assert isinstance(response, generative_settings.GenerativeSettings)
assert response.name == "name_value"
+ assert response.language_code == "language_code_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_validate_agent_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
+def test_get_generative_settings_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_validate_agent"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_validate_agent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.ValidateAgentRequest.pb(agent.ValidateAgentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = agent.AgentValidationResult.to_json(
- agent.AgentValidationResult()
+ # Ensure method has been cached
+ assert (
+ client._transport.get_generative_settings
+ in client._transport._wrapped_methods
)
- req.return_value.content = return_value
- request = agent.ValidateAgentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = agent.AgentValidationResult()
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.get_generative_settings
+ ] = mock_rpc
+
+ request = {}
+ client.get_generative_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_generative_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_get_generative_settings_rest_required_fields(
+ request_type=agent.GetGenerativeSettingsRequest,
+):
+ transport_class = transports.AgentsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request_init["language_code"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+ assert "languageCode" not in jsonified_request
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_generative_settings._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
- client.validate_agent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
+ # verify required fields with default values are now present
+ assert "languageCode" in jsonified_request
+ assert jsonified_request["languageCode"] == request_init["language_code"]
- pre.assert_called_once()
- post.assert_called_once()
+ jsonified_request["name"] = "name_value"
+ jsonified_request["languageCode"] = "language_code_value"
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_generative_settings._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
+ assert "languageCode" in jsonified_request
+ assert jsonified_request["languageCode"] == "language_code_value"
-def test_get_agent_validation_result_rest_bad_request(
- request_type=agent.GetAgentValidationResultRequest,
-):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
- }
request = request_type(**request_init)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_agent_validation_result(request)
+ # Designate an appropriate value for the returned response.
+ return_value = generative_settings.GenerativeSettings()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+ response_value = Response()
+ response_value.status_code = 200
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.GetAgentValidationResultRequest,
- dict,
- ],
-)
-def test_get_agent_validation_result_rest_call_success(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+ # Convert return value to protobuf type
+ return_value = generative_settings.GenerativeSettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/validationResult"
- }
- request = request_type(**request_init)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = agent.AgentValidationResult(
- name="name_value",
- )
+ response = client.get_generative_settings(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [
+ (
+ "languageCode",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = agent.AgentValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_agent_validation_result(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, agent.AgentValidationResult)
- assert response.name == "name_value"
+def test_get_generative_settings_rest_unset_required_fields():
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.get_generative_settings._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("languageCode",))
+ & set(
+ (
+ "name",
+ "languageCode",
+ )
+ )
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_agent_validation_result_rest_interceptors(null_interceptor):
+def test_get_generative_settings_rest_interceptors(null_interceptor):
transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
client = AgentsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_get_agent_validation_result"
+ transports.AgentsRestInterceptor, "post_get_generative_settings"
) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_get_agent_validation_result"
+ transports.AgentsRestInterceptor, "pre_get_generative_settings"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = agent.GetAgentValidationResultRequest.pb(
- agent.GetAgentValidationResultRequest()
+ pb_message = agent.GetGenerativeSettingsRequest.pb(
+ agent.GetGenerativeSettingsRequest()
)
transcode.return_value = {
"method": "post",
@@ -8717,22 +8457,22 @@ def test_get_agent_validation_result_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = agent.AgentValidationResult.to_json(
- agent.AgentValidationResult()
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = generative_settings.GenerativeSettings.to_json(
+ generative_settings.GenerativeSettings()
)
- req.return_value.content = return_value
- request = agent.GetAgentValidationResultRequest()
+ request = agent.GetGenerativeSettingsRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = agent.AgentValidationResult()
+ post.return_value = generative_settings.GenerativeSettings()
- client.get_agent_validation_result(
+ client.get_generative_settings(
request,
metadata=[
("key", "val"),
@@ -8745,11 +8485,13 @@ def test_get_agent_validation_result_rest_interceptors(null_interceptor):
def test_get_generative_settings_rest_bad_request(
- request_type=agent.GetGenerativeSettingsRequest,
+ transport: str = "rest", request_type=agent.GetGenerativeSettingsRequest
):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
"name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
@@ -8761,140 +8503,78 @@ def test_get_generative_settings_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
client.get_generative_settings(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- agent.GetGenerativeSettingsRequest,
- dict,
- ],
-)
-def test_get_generative_settings_rest_call_success(request_type):
+def test_get_generative_settings_rest_flattened():
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = generative_settings.GenerativeSettings(
+ return_value = generative_settings.GenerativeSettings()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
name="name_value",
language_code="language_code_value",
)
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = generative_settings.GenerativeSettings.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_generative_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, generative_settings.GenerativeSettings)
- assert response.name == "name_value"
- assert response.language_code == "language_code_value"
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_generative_settings_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
+ client.get_generative_settings(**mock_args)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_get_generative_settings"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_get_generative_settings"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.GetGenerativeSettingsRequest.pb(
- agent.GetGenerativeSettingsRequest()
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/generativeSettings}"
+ % client.transport._host,
+ args[1],
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = generative_settings.GenerativeSettings.to_json(
- generative_settings.GenerativeSettings()
- )
- req.return_value.content = return_value
- request = agent.GetGenerativeSettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = generative_settings.GenerativeSettings()
+def test_get_generative_settings_rest_flattened_error(transport: str = "rest"):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
client.get_generative_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ agent.GetGenerativeSettingsRequest(),
+ name="name_value",
+ language_code="language_code_value",
)
- pre.assert_called_once()
- post.assert_called_once()
-
-def test_update_generative_settings_rest_bad_request(
- request_type=agent.UpdateGenerativeSettingsRequest,
-):
+def test_get_generative_settings_rest_error():
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # send a request that will satisfy transcoding
- request_init = {
- "generative_settings": {
- "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_generative_settings(request)
@pytest.mark.parametrize(
@@ -8904,9 +8584,10 @@ def test_update_generative_settings_rest_bad_request(
dict,
],
)
-def test_update_generative_settings_rest_call_success(request_type):
+def test_update_generative_settings_rest(request_type):
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -9006,640 +8687,424 @@ def get_message_fields(field):
# Remove fields from the sample request which are not present in the runtime version of the dependency
# Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["generative_settings"][field])):
- del request_init["generative_settings"][field][i][subfield]
- else:
- del request_init["generative_settings"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_generative_settings.GenerativeSettings(
- name="name_value",
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_generative_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_generative_settings.GenerativeSettings)
- assert response.name == "name_value"
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_generative_settings_rest_interceptors(null_interceptor):
- transport = transports.AgentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
- )
- client = AgentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.AgentsRestInterceptor, "post_update_generative_settings"
- ) as post, mock.patch.object(
- transports.AgentsRestInterceptor, "pre_update_generative_settings"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = agent.UpdateGenerativeSettingsRequest.pb(
- agent.UpdateGenerativeSettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_generative_settings.GenerativeSettings.to_json(
- gcdc_generative_settings.GenerativeSettings()
- )
- req.return_value.content = return_value
-
- request = agent.UpdateGenerativeSettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_generative_settings.GenerativeSettings()
-
- client.update_generative_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["generative_settings"][field])):
+ del request_init["generative_settings"][field][i][subfield]
+ else:
+ del request_init["generative_settings"][field][subfield]
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = gcdc_generative_settings.GenerativeSettings(
+ name="name_value",
+ language_code="language_code_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.cancel_operation(request)
+ response = client.update_generative_settings(request)
# Establish that the response is the type that we expect.
- assert response is None
-
+ assert isinstance(response, gcdc_generative_settings.GenerativeSettings)
+ assert response.name == "name_value"
+ assert response.language_code == "language_code_value"
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
+def test_update_generative_settings_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Ensure method has been cached
+ assert (
+ client._transport.update_generative_settings
+ in client._transport._wrapped_methods
+ )
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_generative_settings
+ ] = mock_rpc
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ request = {}
+ client.update_generative_settings(request)
- req.return_value = response_value
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
- response = client.get_operation(request)
+ client.update_generative_settings(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_update_generative_settings_rest_required_fields(
+ request_type=agent.UpdateGenerativeSettingsRequest,
):
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport_class = transports.AgentsRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_generative_settings._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_generative_settings._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("update_mask",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_generative_settings.GenerativeSettings()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "patch",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
- req.return_value = response_value
+ # Convert return value to protobuf type
+ return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- response = client.list_operations(request)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ response = client.update_generative_settings(request)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_initialize_client_w_rest():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+
+def test_update_generative_settings_rest_unset_required_fields():
+ transport = transports.AgentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- assert client is not None
+ unset_fields = transport.update_generative_settings._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("updateMask",)) & set(("generativeSettings",)))
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_agents_empty_call_rest():
- client = AgentsClient(
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_generative_settings_rest_interceptors(null_interceptor):
+ transport = transports.AgentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.AgentsRestInterceptor(),
)
+ client = AgentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.AgentsRestInterceptor, "post_update_generative_settings"
+ ) as post, mock.patch.object(
+ transports.AgentsRestInterceptor, "pre_update_generative_settings"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = agent.UpdateGenerativeSettingsRequest.pb(
+ agent.UpdateGenerativeSettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_agents), "__call__") as call:
- client.list_agents(request=None)
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_generative_settings.GenerativeSettings.to_json(
+ gcdc_generative_settings.GenerativeSettings()
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ListAgentsRequest()
+ request = agent.UpdateGenerativeSettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_generative_settings.GenerativeSettings()
+
+ client.update_generative_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- assert args[0] == request_msg
+ pre.assert_called_once()
+ post.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_agent_empty_call_rest():
+def test_update_generative_settings_rest_bad_request(
+ transport: str = "rest", request_type=agent.UpdateGenerativeSettingsRequest
+):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_agent), "__call__") as call:
- client.get_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentRequest()
+ # send a request that will satisfy transcoding
+ request_init = {
+ "generative_settings": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
+ }
+ }
+ request = request_type(**request_init)
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_generative_settings(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_agent_empty_call_rest():
+def test_update_generative_settings_rest_flattened():
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_agent), "__call__") as call:
- client.create_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.CreateAgentRequest()
-
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_generative_settings.GenerativeSettings()
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "generative_settings": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generativeSettings"
+ }
+ }
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_agent_empty_call_rest():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # get truthy value for each flattened field
+ mock_args = dict(
+ generative_settings=gcdc_generative_settings.GenerativeSettings(
+ name="name_value"
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_agent), "__call__") as call:
- client.update_agent(request=None)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_generative_settings.GenerativeSettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_agent.UpdateAgentRequest()
+ client.update_generative_settings(**mock_args)
- assert args[0] == request_msg
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{generative_settings.name=projects/*/locations/*/agents/*/generativeSettings}"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_agent_empty_call_rest():
+def test_update_generative_settings_rest_flattened_error(transport: str = "rest"):
client = AgentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_agent), "__call__") as call:
- client.delete_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.DeleteAgentRequest()
-
- assert args[0] == request_msg
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_generative_settings(
+ agent.UpdateGenerativeSettingsRequest(),
+ generative_settings=gcdc_generative_settings.GenerativeSettings(
+ name="name_value"
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_agent_empty_call_rest():
+def test_update_generative_settings_rest_error():
client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_agent), "__call__") as call:
- client.export_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ExportAgentRequest()
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_restore_agent_empty_call_rest():
- client = AgentsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.AgentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.restore_agent), "__call__") as call:
- client.restore_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.RestoreAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_validate_agent_empty_call_rest():
- client = AgentsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.AgentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = AgentsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_agent), "__call__") as call:
- client.validate_agent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.ValidateAgentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_agent_validation_result_empty_call_rest():
- client = AgentsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.AgentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = AgentsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_agent_validation_result), "__call__"
- ) as call:
- client.get_agent_validation_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetAgentValidationResultRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = AgentsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_generative_settings_empty_call_rest():
- client = AgentsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.AgentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = AgentsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_generative_settings), "__call__"
- ) as call:
- client.get_generative_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.GetGenerativeSettingsRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AgentsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = AgentsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_generative_settings_empty_call_rest():
- client = AgentsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AgentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_generative_settings), "__call__"
- ) as call:
- client.update_generative_settings(request=None)
+ transport = transports.AgentsGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = agent.UpdateGenerativeSettingsRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AgentsGrpcTransport,
+ transports.AgentsGrpcAsyncIOTransport,
+ transports.AgentsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_agents_rest_lro_client():
- client = AgentsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = AgentsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -9889,15 +9354,32 @@ def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class):
)
-def test_agents_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.AgentsRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_agents_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.AgentsRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_agents_rest_lro_client():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -10387,115 +9869,415 @@ def test_parse_common_billing_account_path():
}
path = AgentsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = AgentsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = AgentsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = AgentsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = AgentsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AgentsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = AgentsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = AgentsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AgentsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = AgentsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = AgentsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AgentsClient.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 = AgentsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = AgentsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AgentsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.AgentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.AgentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = AgentsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = AgentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = AgentsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = AgentsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = AgentsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = AgentsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = AgentsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = AgentsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = AgentsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = AgentsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = AgentsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = AgentsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = AgentsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = AgentsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.AgentsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.AgentsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = AgentsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -10525,7 +10307,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10578,7 +10360,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10623,7 +10405,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -10664,7 +10446,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10719,7 +10501,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10766,7 +10548,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -10809,7 +10591,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10864,7 +10646,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10911,7 +10693,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -10954,7 +10736,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -11009,7 +10791,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -11056,7 +10838,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -11099,7 +10881,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -11151,7 +10933,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = AgentsAsyncClient(credentials=async_anonymous_credentials())
+ client = AgentsAsyncClient(credentials=ga_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.
@@ -11197,7 +10979,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -11213,41 +10995,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = AgentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = AgentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = AgentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py
index f69fc6302051..0187008a5366 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_changelogs.py
@@ -22,38 +22,28 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.location import locations_pb2
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
+from google.protobuf import json_format
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.changelogs import (
ChangelogsAsyncClient,
@@ -64,24 +54,10 @@
from google.cloud.dialogflowcx_v3beta1.types import changelog
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1141,6 +1117,25 @@ def test_list_changelogs(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_changelogs_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 = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_changelogs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == changelog.ListChangelogsRequest()
+
+
def test_list_changelogs_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1208,6 +1203,29 @@ def test_list_changelogs_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_changelogs_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ChangelogsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ changelog.ListChangelogsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_changelogs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == changelog.ListChangelogsRequest()
+
+
@pytest.mark.asyncio
async def test_list_changelogs_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1216,7 +1234,7 @@ async def test_list_changelogs_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1231,23 +1249,27 @@ async def test_list_changelogs_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_changelogs
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_changelogs(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_changelogs(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1255,7 +1277,7 @@ async def test_list_changelogs_async(
transport: str = "grpc_asyncio", request_type=changelog.ListChangelogsRequest
):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1321,7 +1343,7 @@ def test_list_changelogs_field_headers():
@pytest.mark.asyncio
async def test_list_changelogs_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1391,7 +1413,7 @@ def test_list_changelogs_flattened_error():
@pytest.mark.asyncio
async def test_list_changelogs_flattened_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1420,7 +1442,7 @@ async def test_list_changelogs_flattened_async():
@pytest.mark.asyncio
async def test_list_changelogs_flattened_error_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1470,16 +1492,12 @@ def test_list_changelogs_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_changelogs(request={}, retry=retry, timeout=timeout)
+ pager = client.list_changelogs(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1530,7 +1548,7 @@ def test_list_changelogs_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_changelogs_async_pager():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1580,7 +1598,7 @@ async def test_list_changelogs_async_pager():
@pytest.mark.asyncio
async def test_list_changelogs_async_pages():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1674,6 +1692,25 @@ def test_get_changelog(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_get_changelog_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 = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_changelog), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_changelog()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == changelog.GetChangelogRequest()
+
+
def test_get_changelog_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1737,6 +1774,35 @@ def test_get_changelog_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_changelog_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ChangelogsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_changelog), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ changelog.Changelog(
+ name="name_value",
+ user_email="user_email_value",
+ display_name="display_name_value",
+ action="action_value",
+ type_="type__value",
+ resource="resource_value",
+ language_code="language_code_value",
+ )
+ )
+ response = await client.get_changelog()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == changelog.GetChangelogRequest()
+
+
@pytest.mark.asyncio
async def test_get_changelog_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1745,7 +1811,7 @@ async def test_get_changelog_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1760,23 +1826,27 @@ async def test_get_changelog_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_changelog
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_changelog(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_changelog(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1784,7 +1854,7 @@ async def test_get_changelog_async(
transport: str = "grpc_asyncio", request_type=changelog.GetChangelogRequest
):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1862,7 +1932,7 @@ def test_get_changelog_field_headers():
@pytest.mark.asyncio
async def test_get_changelog_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1930,7 +2000,7 @@ def test_get_changelog_flattened_error():
@pytest.mark.asyncio
async def test_get_changelog_flattened_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1957,7 +2027,7 @@ async def test_get_changelog_flattened_async():
@pytest.mark.asyncio
async def test_get_changelog_flattened_error_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1969,6 +2039,46 @@ async def test_get_changelog_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ changelog.ListChangelogsRequest,
+ dict,
+ ],
+)
+def test_list_changelogs_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = changelog.ListChangelogsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = changelog.ListChangelogsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_changelogs(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListChangelogsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_changelogs_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2105,6 +2215,87 @@ def test_list_changelogs_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_changelogs_rest_interceptors(null_interceptor):
+ transport = transports.ChangelogsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ChangelogsRestInterceptor(),
+ )
+ client = ChangelogsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ChangelogsRestInterceptor, "post_list_changelogs"
+ ) as post, mock.patch.object(
+ transports.ChangelogsRestInterceptor, "pre_list_changelogs"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = changelog.ListChangelogsRequest.pb(
+ changelog.ListChangelogsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = changelog.ListChangelogsResponse.to_json(
+ changelog.ListChangelogsResponse()
+ )
+
+ request = changelog.ListChangelogsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = changelog.ListChangelogsResponse()
+
+ client.list_changelogs(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_changelogs_rest_bad_request(
+ transport: str = "rest", request_type=changelog.ListChangelogsRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_changelogs(request)
+
+
def test_list_changelogs_rest_flattened():
client = ChangelogsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -2223,20 +2414,74 @@ def test_list_changelogs_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
-def test_get_changelog_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ changelog.GetChangelogRequest,
+ dict,
+ ],
+)
+def test_get_changelog_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/changelogs/sample4"
+ }
+ request = request_type(**request_init)
- # Ensure method has been cached
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = changelog.Changelog(
+ name="name_value",
+ user_email="user_email_value",
+ display_name="display_name_value",
+ action="action_value",
+ type_="type__value",
+ resource="resource_value",
+ language_code="language_code_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = changelog.Changelog.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_changelog(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, changelog.Changelog)
+ assert response.name == "name_value"
+ assert response.user_email == "user_email_value"
+ assert response.display_name == "display_name_value"
+ assert response.action == "action_value"
+ assert response.type_ == "type__value"
+ assert response.resource == "resource_value"
+ assert response.language_code == "language_code_value"
+
+
+def test_get_changelog_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
assert client._transport.get_changelog in client._transport._wrapped_methods
# Replace cached wrapped function with mock
@@ -2340,6 +2585,85 @@ def test_get_changelog_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_changelog_rest_interceptors(null_interceptor):
+ transport = transports.ChangelogsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ChangelogsRestInterceptor(),
+ )
+ client = ChangelogsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ChangelogsRestInterceptor, "post_get_changelog"
+ ) as post, mock.patch.object(
+ transports.ChangelogsRestInterceptor, "pre_get_changelog"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = changelog.GetChangelogRequest.pb(changelog.GetChangelogRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = changelog.Changelog.to_json(changelog.Changelog())
+
+ request = changelog.GetChangelogRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = changelog.Changelog()
+
+ client.get_changelog(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_changelog_rest_bad_request(
+ transport: str = "rest", request_type=changelog.GetChangelogRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/changelogs/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_changelog(request)
+
+
def test_get_changelog_rest_flattened():
client = ChangelogsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -2399,6 +2723,12 @@ def test_get_changelog_rest_flattened_error(transport: str = "rest"):
)
+def test_get_changelog_rest_error():
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.ChangelogsGrpcTransport(
@@ -2488,735 +2818,21 @@ def test_transport_adc(transport_class):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = ChangelogsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_changelogs_empty_call_grpc():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call:
- call.return_value = changelog.ListChangelogsResponse()
- client.list_changelogs(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.ListChangelogsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_changelog_empty_call_grpc():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_changelog), "__call__") as call:
- call.return_value = changelog.Changelog()
- client.get_changelog(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.GetChangelogRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ChangelogsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_changelogs_empty_call_grpc_asyncio():
- client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- changelog.ListChangelogsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_changelogs(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.ListChangelogsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_changelog_empty_call_grpc_asyncio():
- client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_changelog), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- changelog.Changelog(
- name="name_value",
- user_email="user_email_value",
- display_name="display_name_value",
- action="action_value",
- type_="type__value",
- resource="resource_value",
- language_code="language_code_value",
- )
- )
- await client.get_changelog(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.GetChangelogRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = ChangelogsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_changelogs_rest_bad_request(request_type=changelog.ListChangelogsRequest):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_changelogs(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- changelog.ListChangelogsRequest,
- dict,
- ],
-)
-def test_list_changelogs_rest_call_success(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = changelog.ListChangelogsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = changelog.ListChangelogsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_changelogs(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListChangelogsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_changelogs_rest_interceptors(null_interceptor):
- transport = transports.ChangelogsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ChangelogsRestInterceptor(),
- )
- client = ChangelogsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ChangelogsRestInterceptor, "post_list_changelogs"
- ) as post, mock.patch.object(
- transports.ChangelogsRestInterceptor, "pre_list_changelogs"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = changelog.ListChangelogsRequest.pb(
- changelog.ListChangelogsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = changelog.ListChangelogsResponse.to_json(
- changelog.ListChangelogsResponse()
- )
- req.return_value.content = return_value
-
- request = changelog.ListChangelogsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = changelog.ListChangelogsResponse()
-
- client.list_changelogs(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_changelog_rest_bad_request(request_type=changelog.GetChangelogRequest):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/changelogs/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_changelog(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- changelog.GetChangelogRequest,
- dict,
- ],
-)
-def test_get_changelog_rest_call_success(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/changelogs/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = changelog.Changelog(
- name="name_value",
- user_email="user_email_value",
- display_name="display_name_value",
- action="action_value",
- type_="type__value",
- resource="resource_value",
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = changelog.Changelog.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_changelog(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, changelog.Changelog)
- assert response.name == "name_value"
- assert response.user_email == "user_email_value"
- assert response.display_name == "display_name_value"
- assert response.action == "action_value"
- assert response.type_ == "type__value"
- assert response.resource == "resource_value"
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_changelog_rest_interceptors(null_interceptor):
- transport = transports.ChangelogsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ChangelogsRestInterceptor(),
- )
- client = ChangelogsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ChangelogsRestInterceptor, "post_get_changelog"
- ) as post, mock.patch.object(
- transports.ChangelogsRestInterceptor, "pre_get_changelog"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = changelog.GetChangelogRequest.pb(changelog.GetChangelogRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = changelog.Changelog.to_json(changelog.Changelog())
- req.return_value.content = return_value
-
- request = changelog.GetChangelogRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = changelog.Changelog()
-
- client.get_changelog(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_changelogs_empty_call_rest():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call:
- client.list_changelogs(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.ListChangelogsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_changelog_empty_call_rest():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_changelog), "__call__") as call:
- client.get_changelog(request=None)
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = changelog.GetChangelogRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = ChangelogsClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -3696,115 +3312,415 @@ def test_parse_common_billing_account_path():
}
path = ChangelogsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = ChangelogsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = ChangelogsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = ChangelogsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = ChangelogsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ChangelogsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = ChangelogsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = ChangelogsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ChangelogsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = ChangelogsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = ChangelogsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ChangelogsClient.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 = ChangelogsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = ChangelogsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ChangelogsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ChangelogsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ChangelogsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ChangelogsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = ChangelogsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ChangelogsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = ChangelogsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ChangelogsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = ChangelogsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = ChangelogsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = ChangelogsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ChangelogsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = ChangelogsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ChangelogsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ChangelogsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = ChangelogsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = ChangelogsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.ChangelogsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.ChangelogsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = ChangelogsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -3834,7 +3750,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3887,7 +3803,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3932,7 +3848,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -3973,7 +3889,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4028,7 +3944,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4075,7 +3991,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -4118,7 +4034,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4173,7 +4089,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4220,7 +4136,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -4263,7 +4179,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4318,7 +4234,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4365,7 +4281,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -4408,7 +4324,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4460,7 +4376,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = ChangelogsAsyncClient(credentials=async_anonymous_credentials())
+ client = ChangelogsAsyncClient(credentials=ga_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.
@@ -4506,7 +4422,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -4522,41 +4438,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = ChangelogsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = ChangelogsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = ChangelogsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_conversation_history.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_conversation_history.py
index 851b57f8cc2c..56e770cdfe93 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_conversation_history.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_conversation_history.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,7 +36,15 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.conversation_history import (
ConversationHistoryAsyncClient,
@@ -71,24 +61,10 @@
)
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1259,6 +1235,27 @@ def test_list_conversations(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_conversations_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 = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_conversations), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_conversations()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.ListConversationsRequest()
+
+
def test_list_conversations_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1332,6 +1329,31 @@ def test_list_conversations_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_conversations_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ConversationHistoryAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_conversations), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ conversation_history.ListConversationsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_conversations()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.ListConversationsRequest()
+
+
@pytest.mark.asyncio
async def test_list_conversations_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1340,7 +1362,7 @@ async def test_list_conversations_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1355,23 +1377,27 @@ async def test_list_conversations_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_conversations
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_conversations(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_conversations(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1380,7 +1406,7 @@ async def test_list_conversations_async(
request_type=conversation_history.ListConversationsRequest,
):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1450,7 +1476,7 @@ def test_list_conversations_field_headers():
@pytest.mark.asyncio
async def test_list_conversations_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1524,7 +1550,7 @@ def test_list_conversations_flattened_error():
@pytest.mark.asyncio
async def test_list_conversations_flattened_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1555,7 +1581,7 @@ async def test_list_conversations_flattened_async():
@pytest.mark.asyncio
async def test_list_conversations_flattened_error_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1607,16 +1633,12 @@ def test_list_conversations_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_conversations(request={}, retry=retry, timeout=timeout)
+ pager = client.list_conversations(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1669,7 +1691,7 @@ def test_list_conversations_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_conversations_async_pager():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1721,7 +1743,7 @@ async def test_list_conversations_async_pager():
@pytest.mark.asyncio
async def test_list_conversations_async_pages():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1809,6 +1831,25 @@ def test_get_conversation(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_get_conversation_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 = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_conversation), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_conversation()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.GetConversationRequest()
+
+
def test_get_conversation_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1874,6 +1915,31 @@ def test_get_conversation_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_conversation_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ConversationHistoryAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_conversation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ conversation_history.Conversation(
+ name="name_value",
+ type_=conversation_history.Conversation.Type.AUDIO,
+ language_code="language_code_value",
+ )
+ )
+ response = await client.get_conversation()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.GetConversationRequest()
+
+
@pytest.mark.asyncio
async def test_get_conversation_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1882,7 +1948,7 @@ async def test_get_conversation_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1897,23 +1963,27 @@ async def test_get_conversation_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_conversation
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_conversation(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_conversation(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1922,7 +1992,7 @@ async def test_get_conversation_async(
request_type=conversation_history.GetConversationRequest,
):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1992,7 +2062,7 @@ def test_get_conversation_field_headers():
@pytest.mark.asyncio
async def test_get_conversation_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2062,7 +2132,7 @@ def test_get_conversation_flattened_error():
@pytest.mark.asyncio
async def test_get_conversation_flattened_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2091,7 +2161,7 @@ async def test_get_conversation_flattened_async():
@pytest.mark.asyncio
async def test_get_conversation_flattened_error_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2138,6 +2208,27 @@ def test_delete_conversation(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_conversation_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 = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_conversation), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_conversation()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.DeleteConversationRequest()
+
+
def test_delete_conversation_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2207,6 +2298,27 @@ def test_delete_conversation_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_conversation_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ConversationHistoryAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_conversation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_conversation()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == conversation_history.DeleteConversationRequest()
+
+
@pytest.mark.asyncio
async def test_delete_conversation_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2215,7 +2327,7 @@ async def test_delete_conversation_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2230,23 +2342,27 @@ async def test_delete_conversation_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_conversation
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_conversation(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_conversation(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2255,7 +2371,7 @@ async def test_delete_conversation_async(
request_type=conversation_history.DeleteConversationRequest,
):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2320,7 +2436,7 @@ def test_delete_conversation_field_headers():
@pytest.mark.asyncio
async def test_delete_conversation_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2392,7 +2508,7 @@ def test_delete_conversation_flattened_error():
@pytest.mark.asyncio
async def test_delete_conversation_flattened_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2421,7 +2537,7 @@ async def test_delete_conversation_flattened_async():
@pytest.mark.asyncio
async def test_delete_conversation_flattened_error_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2433,6 +2549,46 @@ async def test_delete_conversation_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ conversation_history.ListConversationsRequest,
+ dict,
+ ],
+)
+def test_list_conversations_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = conversation_history.ListConversationsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = conversation_history.ListConversationsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_conversations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListConversationsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_conversations_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2575,31 +2731,114 @@ def test_list_conversations_rest_unset_required_fields():
)
-def test_list_conversations_rest_flattened():
- client = ConversationHistoryClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_conversations_rest_interceptors(null_interceptor):
+ transport = transports.ConversationHistoryRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ConversationHistoryRestInterceptor(),
)
+ client = ConversationHistoryClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ConversationHistoryRestInterceptor, "post_list_conversations"
+ ) as post, mock.patch.object(
+ transports.ConversationHistoryRestInterceptor, "pre_list_conversations"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = conversation_history.ListConversationsRequest.pb(
+ conversation_history.ListConversationsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = conversation_history.ListConversationsResponse()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ conversation_history.ListConversationsResponse.to_json(
+ conversation_history.ListConversationsResponse()
+ )
+ )
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = conversation_history.ListConversationsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = conversation_history.ListConversationsResponse()
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
+ client.list_conversations(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = conversation_history.ListConversationsResponse.pb(return_value)
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_conversations_rest_bad_request(
+ transport: str = "rest", request_type=conversation_history.ListConversationsRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_conversations(request)
+
+
+def test_list_conversations_rest_flattened():
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = conversation_history.ListConversationsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = conversation_history.ListConversationsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
@@ -2695,6 +2934,52 @@ def test_list_conversations_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ conversation_history.GetConversationRequest,
+ dict,
+ ],
+)
+def test_get_conversation_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = conversation_history.Conversation(
+ name="name_value",
+ type_=conversation_history.Conversation.Type.AUDIO,
+ language_code="language_code_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = conversation_history.Conversation.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_conversation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, conversation_history.Conversation)
+ assert response.name == "name_value"
+ assert response.type_ == conversation_history.Conversation.Type.AUDIO
+ assert response.language_code == "language_code_value"
+
+
def test_get_conversation_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2816,6 +3101,89 @@ def test_get_conversation_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_conversation_rest_interceptors(null_interceptor):
+ transport = transports.ConversationHistoryRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ConversationHistoryRestInterceptor(),
+ )
+ client = ConversationHistoryClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ConversationHistoryRestInterceptor, "post_get_conversation"
+ ) as post, mock.patch.object(
+ transports.ConversationHistoryRestInterceptor, "pre_get_conversation"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = conversation_history.GetConversationRequest.pb(
+ conversation_history.GetConversationRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = conversation_history.Conversation.to_json(
+ conversation_history.Conversation()
+ )
+
+ request = conversation_history.GetConversationRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = conversation_history.Conversation()
+
+ client.get_conversation(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_conversation_rest_bad_request(
+ transport: str = "rest", request_type=conversation_history.GetConversationRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_conversation(request)
+
+
def test_get_conversation_rest_flattened():
client = ConversationHistoryClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -2875,6 +3243,49 @@ def test_get_conversation_rest_flattened_error(transport: str = "rest"):
)
+def test_get_conversation_rest_error():
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ conversation_history.DeleteConversationRequest,
+ dict,
+ ],
+)
+def test_delete_conversation_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_conversation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_conversation_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2995,26 +3406,101 @@ def test_delete_conversation_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_delete_conversation_rest_flattened():
- client = ConversationHistoryClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_conversation_rest_interceptors(null_interceptor):
+ transport = transports.ConversationHistoryRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ConversationHistoryRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ client = ConversationHistoryClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ConversationHistoryRestInterceptor, "pre_delete_conversation"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = conversation_history.DeleteConversationRequest.pb(
+ conversation_history.DeleteConversationRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = conversation_history.DeleteConversationRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_conversation(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_conversation_rest_bad_request(
+ transport: str = "rest", request_type=conversation_history.DeleteConversationRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_conversation(request)
+
+
+def test_delete_conversation_rest_flattened():
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
mock_args.update(sample_request)
# Wrap the value into a proper Response obj
@@ -3052,6 +3538,12 @@ def test_delete_conversation_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_conversation_rest_error():
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.ConversationHistoryGrpcTransport(
@@ -3138,920 +3630,24 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = ConversationHistoryClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_conversations_empty_call_grpc():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_conversations), "__call__"
- ) as call:
- call.return_value = conversation_history.ListConversationsResponse()
- client.list_conversations(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.ListConversationsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_conversation_empty_call_grpc():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_conversation), "__call__") as call:
- call.return_value = conversation_history.Conversation()
- client.get_conversation(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.GetConversationRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_conversation_empty_call_grpc():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_conversation), "__call__"
- ) as call:
- call.return_value = None
- client.delete_conversation(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.DeleteConversationRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ConversationHistoryAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_conversations_empty_call_grpc_asyncio():
- client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_conversations), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- conversation_history.ListConversationsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_conversations(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.ListConversationsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_conversation_empty_call_grpc_asyncio():
- client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_conversation), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- conversation_history.Conversation(
- name="name_value",
- type_=conversation_history.Conversation.Type.AUDIO,
- language_code="language_code_value",
- )
- )
- await client.get_conversation(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.GetConversationRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_conversation_empty_call_grpc_asyncio():
- client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_conversation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_conversation(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.DeleteConversationRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = ConversationHistoryClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_conversations_rest_bad_request(
- request_type=conversation_history.ListConversationsRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_conversations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- conversation_history.ListConversationsRequest,
- dict,
- ],
-)
-def test_list_conversations_rest_call_success(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = conversation_history.ListConversationsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = conversation_history.ListConversationsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_conversations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListConversationsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_conversations_rest_interceptors(null_interceptor):
- transport = transports.ConversationHistoryRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ConversationHistoryRestInterceptor(),
- )
- client = ConversationHistoryClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ConversationHistoryRestInterceptor, "post_list_conversations"
- ) as post, mock.patch.object(
- transports.ConversationHistoryRestInterceptor, "pre_list_conversations"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = conversation_history.ListConversationsRequest.pb(
- conversation_history.ListConversationsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = conversation_history.ListConversationsResponse.to_json(
- conversation_history.ListConversationsResponse()
- )
- req.return_value.content = return_value
-
- request = conversation_history.ListConversationsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = conversation_history.ListConversationsResponse()
-
- client.list_conversations(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_conversation_rest_bad_request(
- request_type=conversation_history.GetConversationRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_conversation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- conversation_history.GetConversationRequest,
- dict,
- ],
-)
-def test_get_conversation_rest_call_success(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = conversation_history.Conversation(
- name="name_value",
- type_=conversation_history.Conversation.Type.AUDIO,
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = conversation_history.Conversation.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_conversation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, conversation_history.Conversation)
- assert response.name == "name_value"
- assert response.type_ == conversation_history.Conversation.Type.AUDIO
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_conversation_rest_interceptors(null_interceptor):
- transport = transports.ConversationHistoryRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ConversationHistoryRestInterceptor(),
- )
- client = ConversationHistoryClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ConversationHistoryRestInterceptor, "post_get_conversation"
- ) as post, mock.patch.object(
- transports.ConversationHistoryRestInterceptor, "pre_get_conversation"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = conversation_history.GetConversationRequest.pb(
- conversation_history.GetConversationRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = conversation_history.Conversation.to_json(
- conversation_history.Conversation()
- )
- req.return_value.content = return_value
-
- request = conversation_history.GetConversationRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = conversation_history.Conversation()
-
- client.get_conversation(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_conversation_rest_bad_request(
- request_type=conversation_history.DeleteConversationRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_conversation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- conversation_history.DeleteConversationRequest,
- dict,
- ],
-)
-def test_delete_conversation_rest_call_success(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/conversations/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_conversation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_conversation_rest_interceptors(null_interceptor):
- transport = transports.ConversationHistoryRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ConversationHistoryRestInterceptor(),
- )
- client = ConversationHistoryClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ConversationHistoryRestInterceptor, "pre_delete_conversation"
- ) as pre:
- pre.assert_not_called()
- pb_message = conversation_history.DeleteConversationRequest.pb(
- conversation_history.DeleteConversationRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = conversation_history.DeleteConversationRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_conversation(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_conversations_empty_call_rest():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_conversations), "__call__"
- ) as call:
- client.list_conversations(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.ListConversationsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_conversation_empty_call_rest():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_conversation), "__call__") as call:
- client.get_conversation(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.GetConversationRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_conversation_empty_call_rest():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_conversation), "__call__"
- ) as call:
- client.delete_conversation(request=None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = conversation_history.DeleteConversationRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = ConversationHistoryClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -5051,110 +4647,410 @@ def test_parse_common_billing_account_path():
assert expected == actual
-def test_common_folder_path():
- folder = "whelk"
- expected = "folders/{folder}".format(
- folder=folder,
+def test_common_folder_path():
+ folder = "whelk"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = ConversationHistoryClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = ConversationHistoryClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConversationHistoryClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = ConversationHistoryClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = ConversationHistoryClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConversationHistoryClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = ConversationHistoryClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = ConversationHistoryClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConversationHistoryClient.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 = ConversationHistoryClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = ConversationHistoryClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConversationHistoryClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ConversationHistoryTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ConversationHistoryTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ConversationHistoryClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = ConversationHistoryAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ConversationHistoryClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "octopus",
- }
- path = ConversationHistoryClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ConversationHistoryClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "oyster"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = ConversationHistoryClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nudibranch",
- }
- path = ConversationHistoryClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = ConversationHistoryClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "cuttlefish"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ConversationHistoryClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "mussel",
- }
- path = ConversationHistoryClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ConversationHistoryClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "winkle"
- location = "nautilus"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ConversationHistoryClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "scallop",
- "location": "abalone",
- }
- path = ConversationHistoryClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = ConversationHistoryClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.ConversationHistoryTransport, "_prep_wrapped_messages"
- ) as prep:
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.ConversationHistoryTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = ConversationHistoryClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -5184,7 +5080,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5237,7 +5133,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5282,7 +5178,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -5323,7 +5219,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5378,7 +5274,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5425,7 +5321,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -5468,7 +5364,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5523,7 +5419,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5570,7 +5466,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -5613,7 +5509,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5668,7 +5564,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5715,7 +5611,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -5758,7 +5654,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5812,7 +5708,9 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = ConversationHistoryAsyncClient(credentials=async_anonymous_credentials())
+ client = ConversationHistoryAsyncClient(
+ credentials=ga_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.
@@ -5858,7 +5756,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -5874,41 +5772,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = ConversationHistoryAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = ConversationHistoryClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = ConversationHistoryClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py
index 22f52a60618e..3cd5750906c0 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py
@@ -22,38 +22,28 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.location import locations_pb2
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
+from google.protobuf import json_format
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.deployments import (
DeploymentsAsyncClient,
@@ -64,24 +54,10 @@
from google.cloud.dialogflowcx_v3beta1.types import deployment
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1145,6 +1121,25 @@ def test_list_deployments(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_deployments_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 = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_deployments), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_deployments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == deployment.ListDeploymentsRequest()
+
+
def test_list_deployments_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1212,6 +1207,29 @@ def test_list_deployments_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_deployments_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DeploymentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_deployments), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ deployment.ListDeploymentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_deployments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == deployment.ListDeploymentsRequest()
+
+
@pytest.mark.asyncio
async def test_list_deployments_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1220,7 +1238,7 @@ async def test_list_deployments_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1235,23 +1253,27 @@ async def test_list_deployments_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_deployments
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_deployments(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_deployments(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1259,7 +1281,7 @@ async def test_list_deployments_async(
transport: str = "grpc_asyncio", request_type=deployment.ListDeploymentsRequest
):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1325,7 +1347,7 @@ def test_list_deployments_field_headers():
@pytest.mark.asyncio
async def test_list_deployments_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1395,7 +1417,7 @@ def test_list_deployments_flattened_error():
@pytest.mark.asyncio
async def test_list_deployments_flattened_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1424,7 +1446,7 @@ async def test_list_deployments_flattened_async():
@pytest.mark.asyncio
async def test_list_deployments_flattened_error_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1474,16 +1496,12 @@ def test_list_deployments_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_deployments(request={}, retry=retry, timeout=timeout)
+ pager = client.list_deployments(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1534,7 +1552,7 @@ def test_list_deployments_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_deployments_async_pager():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1584,7 +1602,7 @@ async def test_list_deployments_async_pager():
@pytest.mark.asyncio
async def test_list_deployments_async_pages():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1670,6 +1688,25 @@ def test_get_deployment(request_type, transport: str = "grpc"):
assert response.state == deployment.Deployment.State.RUNNING
+def test_get_deployment_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 = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_deployment), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_deployment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == deployment.GetDeploymentRequest()
+
+
def test_get_deployment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1733,6 +1770,31 @@ def test_get_deployment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_deployment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DeploymentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_deployment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ deployment.Deployment(
+ name="name_value",
+ flow_version="flow_version_value",
+ state=deployment.Deployment.State.RUNNING,
+ )
+ )
+ response = await client.get_deployment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == deployment.GetDeploymentRequest()
+
+
@pytest.mark.asyncio
async def test_get_deployment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1741,7 +1803,7 @@ async def test_get_deployment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1756,23 +1818,27 @@ async def test_get_deployment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_deployment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_deployment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_deployment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1780,7 +1846,7 @@ async def test_get_deployment_async(
transport: str = "grpc_asyncio", request_type=deployment.GetDeploymentRequest
):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1850,7 +1916,7 @@ def test_get_deployment_field_headers():
@pytest.mark.asyncio
async def test_get_deployment_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1920,7 +1986,7 @@ def test_get_deployment_flattened_error():
@pytest.mark.asyncio
async def test_get_deployment_flattened_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1949,7 +2015,7 @@ async def test_get_deployment_flattened_async():
@pytest.mark.asyncio
async def test_get_deployment_flattened_error_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1961,6 +2027,48 @@ async def test_get_deployment_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ deployment.ListDeploymentsRequest,
+ dict,
+ ],
+)
+def test_list_deployments_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = deployment.ListDeploymentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = deployment.ListDeploymentsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_deployments(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListDeploymentsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_deployments_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2097,6 +2205,89 @@ def test_list_deployments_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_deployments_rest_interceptors(null_interceptor):
+ transport = transports.DeploymentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DeploymentsRestInterceptor(),
+ )
+ client = DeploymentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.DeploymentsRestInterceptor, "post_list_deployments"
+ ) as post, mock.patch.object(
+ transports.DeploymentsRestInterceptor, "pre_list_deployments"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = deployment.ListDeploymentsRequest.pb(
+ deployment.ListDeploymentsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = deployment.ListDeploymentsResponse.to_json(
+ deployment.ListDeploymentsResponse()
+ )
+
+ request = deployment.ListDeploymentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = deployment.ListDeploymentsResponse()
+
+ client.list_deployments(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_deployments_rest_bad_request(
+ transport: str = "rest", request_type=deployment.ListDeploymentsRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_deployments(request)
+
+
def test_list_deployments_rest_flattened():
client = DeploymentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -2221,21 +2412,67 @@ def test_list_deployments_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
-def test_get_deployment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ deployment.GetDeploymentRequest,
+ dict,
+ ],
+)
+def test_get_deployment_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/deployments/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = deployment.Deployment(
+ name="name_value",
+ flow_version="flow_version_value",
+ state=deployment.Deployment.State.RUNNING,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = deployment.Deployment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_deployment(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, deployment.Deployment)
+ assert response.name == "name_value"
+ assert response.flow_version == "flow_version_value"
+ assert response.state == deployment.Deployment.State.RUNNING
- # Ensure method has been cached
- assert client._transport.get_deployment in client._transport._wrapped_methods
+
+def test_get_deployment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_deployment in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
@@ -2340,6 +2577,89 @@ def test_get_deployment_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_deployment_rest_interceptors(null_interceptor):
+ transport = transports.DeploymentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DeploymentsRestInterceptor(),
+ )
+ client = DeploymentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.DeploymentsRestInterceptor, "post_get_deployment"
+ ) as post, mock.patch.object(
+ transports.DeploymentsRestInterceptor, "pre_get_deployment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = deployment.GetDeploymentRequest.pb(
+ deployment.GetDeploymentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = deployment.Deployment.to_json(
+ deployment.Deployment()
+ )
+
+ request = deployment.GetDeploymentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = deployment.Deployment()
+
+ client.get_deployment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_deployment_rest_bad_request(
+ transport: str = "rest", request_type=deployment.GetDeploymentRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/deployments/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_deployment(request)
+
+
def test_get_deployment_rest_flattened():
client = DeploymentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -2399,6 +2719,12 @@ def test_get_deployment_rest_flattened_error(transport: str = "rest"):
)
+def test_get_deployment_rest_error():
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.DeploymentsGrpcTransport(
@@ -2488,731 +2814,21 @@ def test_transport_adc(transport_class):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = DeploymentsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_deployments_empty_call_grpc():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_deployments), "__call__") as call:
- call.return_value = deployment.ListDeploymentsResponse()
- client.list_deployments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.ListDeploymentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_deployment_empty_call_grpc():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_deployment), "__call__") as call:
- call.return_value = deployment.Deployment()
- client.get_deployment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.GetDeploymentRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = DeploymentsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_deployments_empty_call_grpc_asyncio():
- client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_deployments), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- deployment.ListDeploymentsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_deployments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.ListDeploymentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_deployment_empty_call_grpc_asyncio():
- client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_deployment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- deployment.Deployment(
- name="name_value",
- flow_version="flow_version_value",
- state=deployment.Deployment.State.RUNNING,
- )
- )
- await client.get_deployment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.GetDeploymentRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = DeploymentsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_deployments_rest_bad_request(
- request_type=deployment.ListDeploymentsRequest,
-):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_deployments(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- deployment.ListDeploymentsRequest,
- dict,
- ],
-)
-def test_list_deployments_rest_call_success(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = deployment.ListDeploymentsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = deployment.ListDeploymentsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_deployments(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListDeploymentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_deployments_rest_interceptors(null_interceptor):
- transport = transports.DeploymentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.DeploymentsRestInterceptor(),
- )
- client = DeploymentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.DeploymentsRestInterceptor, "post_list_deployments"
- ) as post, mock.patch.object(
- transports.DeploymentsRestInterceptor, "pre_list_deployments"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = deployment.ListDeploymentsRequest.pb(
- deployment.ListDeploymentsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = deployment.ListDeploymentsResponse.to_json(
- deployment.ListDeploymentsResponse()
- )
- req.return_value.content = return_value
-
- request = deployment.ListDeploymentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = deployment.ListDeploymentsResponse()
-
- client.list_deployments(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_deployment_rest_bad_request(request_type=deployment.GetDeploymentRequest):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/deployments/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_deployment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- deployment.GetDeploymentRequest,
- dict,
- ],
-)
-def test_get_deployment_rest_call_success(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/deployments/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = deployment.Deployment(
- name="name_value",
- flow_version="flow_version_value",
- state=deployment.Deployment.State.RUNNING,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = deployment.Deployment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_deployment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, deployment.Deployment)
- assert response.name == "name_value"
- assert response.flow_version == "flow_version_value"
- assert response.state == deployment.Deployment.State.RUNNING
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_deployment_rest_interceptors(null_interceptor):
- transport = transports.DeploymentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.DeploymentsRestInterceptor(),
- )
- client = DeploymentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.DeploymentsRestInterceptor, "post_get_deployment"
- ) as post, mock.patch.object(
- transports.DeploymentsRestInterceptor, "pre_get_deployment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = deployment.GetDeploymentRequest.pb(
- deployment.GetDeploymentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = deployment.Deployment.to_json(deployment.Deployment())
- req.return_value.content = return_value
-
- request = deployment.GetDeploymentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = deployment.Deployment()
-
- client.get_deployment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_deployments_empty_call_rest():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_deployments), "__call__") as call:
- client.list_deployments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.ListDeploymentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_deployment_empty_call_rest():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_deployment), "__call__") as call:
- client.get_deployment(request=None)
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = deployment.GetDeploymentRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = DeploymentsClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -3797,115 +3413,415 @@ def test_parse_common_billing_account_path():
}
path = DeploymentsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = DeploymentsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = DeploymentsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = DeploymentsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = DeploymentsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DeploymentsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = DeploymentsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nautilus",
+ }
+ path = DeploymentsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DeploymentsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "scallop"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = DeploymentsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "abalone",
+ }
+ path = DeploymentsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DeploymentsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = DeploymentsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = DeploymentsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DeploymentsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.DeploymentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.DeploymentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = DeploymentsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = DeploymentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = DeploymentsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = DeploymentsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = DeploymentsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = DeploymentsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = DeploymentsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = DeploymentsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = DeploymentsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = DeploymentsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = DeploymentsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = DeploymentsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = DeploymentsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = DeploymentsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.DeploymentsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.DeploymentsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = DeploymentsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -3935,7 +3851,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3988,7 +3904,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4033,7 +3949,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -4074,7 +3990,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4129,7 +4045,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4176,7 +4092,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -4219,7 +4135,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4274,7 +4190,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4321,7 +4237,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -4364,7 +4280,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4419,7 +4335,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4466,7 +4382,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -4509,7 +4425,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4561,7 +4477,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = DeploymentsAsyncClient(credentials=async_anonymous_credentials())
+ client = DeploymentsAsyncClient(credentials=ga_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.
@@ -4607,7 +4523,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -4623,41 +4539,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = DeploymentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = DeploymentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = DeploymentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py
index c08d5bc7698e..f310ee028130 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -63,6 +45,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.entity_types import (
EntityTypesAsyncClient,
@@ -75,24 +65,10 @@
from google.cloud.dialogflowcx_v3beta1.types import inline
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1169,6 +1145,25 @@ def test_get_entity_type(request_type, transport: str = "grpc"):
assert response.redact is True
+def test_get_entity_type_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.GetEntityTypeRequest()
+
+
def test_get_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1234,6 +1229,34 @@ def test_get_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+ )
+ response = await client.get_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.GetEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_get_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1242,7 +1265,7 @@ async def test_get_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1257,23 +1280,27 @@ async def test_get_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1281,7 +1308,7 @@ async def test_get_entity_type_async(
transport: str = "grpc_asyncio", request_type=entity_type.GetEntityTypeRequest
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1360,7 +1387,7 @@ def test_get_entity_type_field_headers():
@pytest.mark.asyncio
async def test_get_entity_type_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1430,7 +1457,7 @@ def test_get_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_get_entity_type_flattened_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1459,7 +1486,7 @@ async def test_get_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_get_entity_type_flattened_error_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1522,6 +1549,27 @@ def test_create_entity_type(request_type, transport: str = "grpc"):
assert response.redact is True
+def test_create_entity_type_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_entity_type.CreateEntityTypeRequest()
+
+
def test_create_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1593,6 +1641,36 @@ def test_create_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+ )
+ response = await client.create_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_entity_type.CreateEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_create_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1601,7 +1679,7 @@ async def test_create_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1616,23 +1694,27 @@ async def test_create_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1641,7 +1723,7 @@ async def test_create_entity_type_async(
request_type=gcdc_entity_type.CreateEntityTypeRequest,
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1724,7 +1806,7 @@ def test_create_entity_type_field_headers():
@pytest.mark.asyncio
async def test_create_entity_type_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1803,7 +1885,7 @@ def test_create_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_create_entity_type_flattened_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1838,7 +1920,7 @@ async def test_create_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_create_entity_type_flattened_error_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1902,6 +1984,27 @@ def test_update_entity_type(request_type, transport: str = "grpc"):
assert response.redact is True
+def test_update_entity_type_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest()
+
+
def test_update_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1971,6 +2074,36 @@ def test_update_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+ )
+ response = await client.update_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_update_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1979,7 +2112,7 @@ async def test_update_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1994,23 +2127,27 @@ async def test_update_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2019,7 +2156,7 @@ async def test_update_entity_type_async(
request_type=gcdc_entity_type.UpdateEntityTypeRequest,
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2102,7 +2239,7 @@ def test_update_entity_type_field_headers():
@pytest.mark.asyncio
async def test_update_entity_type_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2181,7 +2318,7 @@ def test_update_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_update_entity_type_flattened_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2216,7 +2353,7 @@ async def test_update_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_update_entity_type_flattened_error_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2264,6 +2401,27 @@ def test_delete_entity_type(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_entity_type_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.DeleteEntityTypeRequest()
+
+
def test_delete_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2333,6 +2491,27 @@ def test_delete_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.DeleteEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_delete_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2341,7 +2520,7 @@ async def test_delete_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2356,23 +2535,27 @@ async def test_delete_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2380,7 +2563,7 @@ async def test_delete_entity_type_async(
transport: str = "grpc_asyncio", request_type=entity_type.DeleteEntityTypeRequest
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2445,7 +2628,7 @@ def test_delete_entity_type_field_headers():
@pytest.mark.asyncio
async def test_delete_entity_type_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2517,7 +2700,7 @@ def test_delete_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_delete_entity_type_flattened_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2546,7 +2729,7 @@ async def test_delete_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_delete_entity_type_flattened_error_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2596,6 +2779,27 @@ def test_list_entity_types(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_entity_types_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_entity_types), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ListEntityTypesRequest()
+
+
def test_list_entity_types_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2667,6 +2871,31 @@ def test_list_entity_types_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_entity_types_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_entity_types), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ entity_type.ListEntityTypesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ListEntityTypesRequest()
+
+
@pytest.mark.asyncio
async def test_list_entity_types_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2675,7 +2904,7 @@ async def test_list_entity_types_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2690,23 +2919,27 @@ async def test_list_entity_types_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_entity_types
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_entity_types(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_entity_types(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2714,7 +2947,7 @@ async def test_list_entity_types_async(
transport: str = "grpc_asyncio", request_type=entity_type.ListEntityTypesRequest
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2784,7 +3017,7 @@ def test_list_entity_types_field_headers():
@pytest.mark.asyncio
async def test_list_entity_types_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2858,7 +3091,7 @@ def test_list_entity_types_flattened_error():
@pytest.mark.asyncio
async def test_list_entity_types_flattened_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2889,7 +3122,7 @@ async def test_list_entity_types_flattened_async():
@pytest.mark.asyncio
async def test_list_entity_types_flattened_error_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2941,16 +3174,12 @@ def test_list_entity_types_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_entity_types(request={}, retry=retry, timeout=timeout)
+ pager = client.list_entity_types(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -3003,7 +3232,7 @@ def test_list_entity_types_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_entity_types_async_pager():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3055,7 +3284,7 @@ async def test_list_entity_types_async_pager():
@pytest.mark.asyncio
async def test_list_entity_types_async_pages():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3138,6 +3367,27 @@ def test_export_entity_types(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_entity_types_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.export_entity_types), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ExportEntityTypesRequest()
+
+
def test_export_entity_types_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3204,9 +3454,8 @@ def test_export_entity_types_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_entity_types(request)
@@ -3216,6 +3465,29 @@ def test_export_entity_types_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_entity_types_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.export_entity_types), "__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.export_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ExportEntityTypesRequest()
+
+
@pytest.mark.asyncio
async def test_export_entity_types_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3224,7 +3496,7 @@ async def test_export_entity_types_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3239,28 +3511,31 @@ async def test_export_entity_types_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_entity_types
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_entity_types(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_entity_types(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3268,7 +3543,7 @@ async def test_export_entity_types_async(
transport: str = "grpc_asyncio", request_type=entity_type.ExportEntityTypesRequest
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3335,7 +3610,7 @@ def test_export_entity_types_field_headers():
@pytest.mark.asyncio
async def test_export_entity_types_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3401,6 +3676,27 @@ def test_import_entity_types(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_import_entity_types_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 = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.import_entity_types), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.import_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ImportEntityTypesRequest()
+
+
def test_import_entity_types_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3467,9 +3763,8 @@ def test_import_entity_types_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.import_entity_types(request)
@@ -3479,6 +3774,29 @@ def test_import_entity_types_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_import_entity_types_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.import_entity_types), "__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.import_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == entity_type.ImportEntityTypesRequest()
+
+
@pytest.mark.asyncio
async def test_import_entity_types_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3487,7 +3805,7 @@ async def test_import_entity_types_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3502,28 +3820,31 @@ async def test_import_entity_types_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.import_entity_types
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.import_entity_types(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.import_entity_types(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3531,7 +3852,7 @@ async def test_import_entity_types_async(
transport: str = "grpc_asyncio", request_type=entity_type.ImportEntityTypesRequest
):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3598,7 +3919,7 @@ def test_import_entity_types_field_headers():
@pytest.mark.asyncio
async def test_import_entity_types_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3629,6 +3950,61 @@ async def test_import_entity_types_field_headers_async():
) in kw["metadata"]
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ entity_type.GetEntityTypeRequest,
+ dict,
+ ],
+)
+def test_get_entity_type_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = entity_type.EntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, entity_type.EntityType)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.kind == entity_type.EntityType.Kind.KIND_MAP
+ assert (
+ response.auto_expansion_mode
+ == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
+ )
+ assert response.enable_fuzzy_extraction is True
+ assert response.redact is True
+
+
def test_get_entity_type_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3750,6 +4126,89 @@ def test_get_entity_type_rest_unset_required_fields():
assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "post_get_entity_type"
+ ) as post, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_get_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = entity_type.GetEntityTypeRequest.pb(
+ entity_type.GetEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = entity_type.EntityType.to_json(
+ entity_type.EntityType()
+ )
+
+ request = entity_type.GetEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = entity_type.EntityType()
+
+ client.get_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_entity_type_rest_bad_request(
+ transport: str = "rest", request_type=entity_type.GetEntityTypeRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_entity_type(request)
+
+
def test_get_entity_type_rest_flattened():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3809,25 +4268,163 @@ def test_get_entity_type_rest_flattened_error(transport: str = "rest"):
)
-def test_create_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_get_entity_type_rest_error():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
- # Ensure method has been cached
- assert (
- client._transport.create_entity_type in client._transport._wrapped_methods
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_entity_type.CreateEntityTypeRequest,
+ dict,
+ ],
+)
+def test_create_entity_type_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Replace cached wrapped function with mock
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["entity_type"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "kind": 1,
+ "auto_expansion_mode": 1,
+ "entities": [
+ {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
+ ],
+ "excluded_phrases": [{"value": "value_value"}],
+ "enable_fuzzy_extraction": True,
+ "redact": True,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_entity_type.CreateEntityTypeRequest.meta.fields["entity_type"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["entity_type"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["entity_type"][field])):
+ del request_init["entity_type"][field][i][subfield]
+ else:
+ del request_init["entity_type"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_entity_type.EntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_entity_type.EntityType)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP
+ assert (
+ response.auto_expansion_mode
+ == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
+ )
+ assert response.enable_fuzzy_extraction is True
+ assert response.redact is True
+
+
+def test_create_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.create_entity_type in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
@@ -3943,6 +4540,87 @@ def test_create_entity_type_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "post_create_entity_type"
+ ) as post, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_create_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_entity_type.CreateEntityTypeRequest.pb(
+ gcdc_entity_type.CreateEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_entity_type.EntityType.to_json(
+ gcdc_entity_type.EntityType()
+ )
+
+ request = gcdc_entity_type.CreateEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_entity_type.EntityType()
+
+ client.create_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_entity_type_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_entity_type.CreateEntityTypeRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_entity_type(request)
+
+
def test_create_entity_type_rest_flattened():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4002,35 +4680,177 @@ def test_create_entity_type_rest_flattened_error(transport: str = "rest"):
)
-def test_update_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.update_entity_type in client._transport._wrapped_methods
- )
+def test_create_entity_type_rest_error():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.update_entity_type
- ] = mock_rpc
- request = {}
- client.update_entity_type(request)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_entity_type.UpdateEntityTypeRequest,
+ dict,
+ ],
+)
+def test_update_entity_type_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "entity_type": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ }
+ request_init["entity_type"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4",
+ "display_name": "display_name_value",
+ "kind": 1,
+ "auto_expansion_mode": 1,
+ "entities": [
+ {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
+ ],
+ "excluded_phrases": [{"value": "value_value"}],
+ "enable_fuzzy_extraction": True,
+ "redact": True,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_entity_type.UpdateEntityTypeRequest.meta.fields["entity_type"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["entity_type"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["entity_type"][field])):
+ del request_init["entity_type"][field][i][subfield]
+ else:
+ del request_init["entity_type"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_entity_type.EntityType(
+ name="name_value",
+ display_name="display_name_value",
+ kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
+ auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
+ enable_fuzzy_extraction=True,
+ redact=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_entity_type.EntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_entity_type.EntityType)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP
+ assert (
+ response.auto_expansion_mode
+ == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
+ )
+ assert response.enable_fuzzy_extraction is True
+ assert response.redact is True
+
+
+def test_update_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_entity_type in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_entity_type
+ ] = mock_rpc
+
+ request = {}
+ client.update_entity_type(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
@@ -4136,6 +4956,91 @@ def test_update_entity_type_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "post_update_entity_type"
+ ) as post, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_update_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_entity_type.UpdateEntityTypeRequest.pb(
+ gcdc_entity_type.UpdateEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_entity_type.EntityType.to_json(
+ gcdc_entity_type.EntityType()
+ )
+
+ request = gcdc_entity_type.UpdateEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_entity_type.EntityType()
+
+ client.update_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_entity_type_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_entity_type.UpdateEntityTypeRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "entity_type": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_entity_type(request)
+
+
def test_update_entity_type_rest_flattened():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4199,27 +5104,70 @@ def test_update_entity_type_rest_flattened_error(transport: str = "rest"):
)
-def test_delete_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+def test_update_entity_type_rest_error():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Ensure method has been cached
- assert (
- client._transport.delete_entity_type in client._transport._wrapped_methods
- )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ entity_type.DeleteEntityTypeRequest,
+ dict,
+ ],
+)
+def test_delete_entity_type_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.delete_entity_type in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
@@ -4321,6 +5269,81 @@ def test_delete_entity_type_rest_unset_required_fields():
assert set(unset_fields) == (set(("force",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_delete_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = entity_type.DeleteEntityTypeRequest.pb(
+ entity_type.DeleteEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = entity_type.DeleteEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_entity_type_rest_bad_request(
+ transport: str = "rest", request_type=entity_type.DeleteEntityTypeRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_entity_type(request)
+
+
def test_delete_entity_type_rest_flattened():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4378,6 +5401,52 @@ def test_delete_entity_type_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_entity_type_rest_error():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ entity_type.ListEntityTypesRequest,
+ dict,
+ ],
+)
+def test_list_entity_types_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = entity_type.ListEntityTypesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = entity_type.ListEntityTypesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_entity_types(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListEntityTypesPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_entity_types_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4516,6 +5585,87 @@ def test_list_entity_types_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_entity_types_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "post_list_entity_types"
+ ) as post, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_list_entity_types"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = entity_type.ListEntityTypesRequest.pb(
+ entity_type.ListEntityTypesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = entity_type.ListEntityTypesResponse.to_json(
+ entity_type.ListEntityTypesResponse()
+ )
+
+ request = entity_type.ListEntityTypesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = entity_type.ListEntityTypesResponse()
+
+ client.list_entity_types(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_entity_types_rest_bad_request(
+ transport: str = "rest", request_type=entity_type.ListEntityTypesRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_entity_types(request)
+
+
def test_list_entity_types_rest_flattened():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4636,12 +5786,47 @@ def test_list_entity_types_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
-def test_export_entity_types_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ entity_type.ExportEntityTypesRequest,
+ dict,
+ ],
+)
+def test_export_entity_types_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.export_entity_types(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_export_entity_types_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
@@ -4773,6 +5958,130 @@ def test_export_entity_types_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_entity_types_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
+ )
+ client = EntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.EntityTypesRestInterceptor, "post_export_entity_types"
+ ) as post, mock.patch.object(
+ transports.EntityTypesRestInterceptor, "pre_export_entity_types"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = entity_type.ExportEntityTypesRequest.pb(
+ entity_type.ExportEntityTypesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
+
+ request = entity_type.ExportEntityTypesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
+
+ client.export_entity_types(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_export_entity_types_rest_bad_request(
+ transport: str = "rest", request_type=entity_type.ExportEntityTypesRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.export_entity_types(request)
+
+
+def test_export_entity_types_rest_error():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ entity_type.ImportEntityTypesRequest,
+ dict,
+ ],
+)
+def test_import_entity_types_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.import_entity_types(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
def test_import_entity_types_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4906,1483 +6215,15 @@ def test_import_entity_types_rest_unset_required_fields():
)
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.EntityTypesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.EntityTypesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EntityTypesClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.EntityTypesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = EntityTypesClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = EntityTypesClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.EntityTypesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EntityTypesClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EntityTypesGrpcTransport(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_import_entity_types_rest_interceptors(null_interceptor):
+ transport = transports.EntityTypesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EntityTypesRestInterceptor(),
)
client = EntityTypesClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EntityTypesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.EntityTypesGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.EntityTypesGrpcTransport,
- transports.EntityTypesGrpcAsyncIOTransport,
- transports.EntityTypesRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = EntityTypesClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_entity_type_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call:
- call.return_value = entity_type.EntityType()
- client.get_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.GetEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_entity_type_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_entity_type), "__call__"
- ) as call:
- call.return_value = gcdc_entity_type.EntityType()
- client.create_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.CreateEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_entity_type_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_entity_type), "__call__"
- ) as call:
- call.return_value = gcdc_entity_type.EntityType()
- client.update_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.UpdateEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_entity_type_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_entity_type), "__call__"
- ) as call:
- call.return_value = None
- client.delete_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.DeleteEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_entity_types_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_entity_types), "__call__"
- ) as call:
- call.return_value = entity_type.ListEntityTypesResponse()
- client.list_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ListEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_entity_types_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_entity_types), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ExportEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_entity_types_empty_call_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_entity_types), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.import_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ImportEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = EntityTypesAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_entity_type_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
- )
- await client.get_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.GetEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_entity_type_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
- )
- await client.create_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.CreateEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_entity_type_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
- )
- await client.update_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.UpdateEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_entity_type_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.DeleteEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_entity_types_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_entity_types), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- entity_type.ListEntityTypesResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ListEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_entity_types_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_entity_types), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.export_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ExportEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_import_entity_types_empty_call_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_entity_types), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.import_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ImportEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = EntityTypesClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_get_entity_type_rest_bad_request(
- request_type=entity_type.GetEntityTypeRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- entity_type.GetEntityTypeRequest,
- dict,
- ],
-)
-def test_get_entity_type_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = entity_type.EntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, entity_type.EntityType)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.kind == entity_type.EntityType.Kind.KIND_MAP
- assert (
- response.auto_expansion_mode
- == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
- )
- assert response.enable_fuzzy_extraction is True
- assert response.redact is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_entity_type_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EntityTypesRestInterceptor, "post_get_entity_type"
- ) as post, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_get_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = entity_type.GetEntityTypeRequest.pb(
- entity_type.GetEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = entity_type.EntityType.to_json(entity_type.EntityType())
- req.return_value.content = return_value
-
- request = entity_type.GetEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = entity_type.EntityType()
-
- client.get_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_entity_type_rest_bad_request(
- request_type=gcdc_entity_type.CreateEntityTypeRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_entity_type.CreateEntityTypeRequest,
- dict,
- ],
-)
-def test_create_entity_type_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["entity_type"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "kind": 1,
- "auto_expansion_mode": 1,
- "entities": [
- {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
- ],
- "excluded_phrases": [{"value": "value_value"}],
- "enable_fuzzy_extraction": True,
- "redact": True,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_entity_type.CreateEntityTypeRequest.meta.fields["entity_type"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["entity_type"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["entity_type"][field])):
- del request_init["entity_type"][field][i][subfield]
- else:
- del request_init["entity_type"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_entity_type.EntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_entity_type.EntityType)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP
- assert (
- response.auto_expansion_mode
- == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
- )
- assert response.enable_fuzzy_extraction is True
- assert response.redact is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_entity_type_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EntityTypesRestInterceptor, "post_create_entity_type"
- ) as post, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_create_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_entity_type.CreateEntityTypeRequest.pb(
- gcdc_entity_type.CreateEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_entity_type.EntityType.to_json(
- gcdc_entity_type.EntityType()
- )
- req.return_value.content = return_value
-
- request = gcdc_entity_type.CreateEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_entity_type.EntityType()
-
- client.create_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_entity_type_rest_bad_request(
- request_type=gcdc_entity_type.UpdateEntityTypeRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "entity_type": {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_entity_type.UpdateEntityTypeRequest,
- dict,
- ],
-)
-def test_update_entity_type_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "entity_type": {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- }
- request_init["entity_type"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4",
- "display_name": "display_name_value",
- "kind": 1,
- "auto_expansion_mode": 1,
- "entities": [
- {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
- ],
- "excluded_phrases": [{"value": "value_value"}],
- "enable_fuzzy_extraction": True,
- "redact": True,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_entity_type.UpdateEntityTypeRequest.meta.fields["entity_type"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["entity_type"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["entity_type"][field])):
- del request_init["entity_type"][field][i][subfield]
- else:
- del request_init["entity_type"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_entity_type.EntityType(
- name="name_value",
- display_name="display_name_value",
- kind=gcdc_entity_type.EntityType.Kind.KIND_MAP,
- auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT,
- enable_fuzzy_extraction=True,
- redact=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_entity_type.EntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_entity_type.EntityType)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP
- assert (
- response.auto_expansion_mode
- == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT
- )
- assert response.enable_fuzzy_extraction is True
- assert response.redact is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_entity_type_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EntityTypesRestInterceptor, "post_update_entity_type"
- ) as post, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_update_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_entity_type.UpdateEntityTypeRequest.pb(
- gcdc_entity_type.UpdateEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_entity_type.EntityType.to_json(
- gcdc_entity_type.EntityType()
- )
- req.return_value.content = return_value
-
- request = gcdc_entity_type.UpdateEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_entity_type.EntityType()
-
- client.update_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_entity_type_rest_bad_request(
- request_type=entity_type.DeleteEntityTypeRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- entity_type.DeleteEntityTypeRequest,
- dict,
- ],
-)
-def test_delete_entity_type_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/entityTypes/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_entity_type_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_delete_entity_type"
- ) as pre:
- pre.assert_not_called()
- pb_message = entity_type.DeleteEntityTypeRequest.pb(
- entity_type.DeleteEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = entity_type.DeleteEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_list_entity_types_rest_bad_request(
- request_type=entity_type.ListEntityTypesRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_entity_types(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- entity_type.ListEntityTypesRequest,
- dict,
- ],
-)
-def test_list_entity_types_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = entity_type.ListEntityTypesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = entity_type.ListEntityTypesResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_entity_types(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListEntityTypesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_entity_types_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EntityTypesRestInterceptor, "post_list_entity_types"
- ) as post, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_list_entity_types"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = entity_type.ListEntityTypesRequest.pb(
- entity_type.ListEntityTypesRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = entity_type.ListEntityTypesResponse.to_json(
- entity_type.ListEntityTypesResponse()
- )
- req.return_value.content = return_value
-
- request = entity_type.ListEntityTypesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = entity_type.ListEntityTypesResponse()
-
- client.list_entity_types(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_export_entity_types_rest_bad_request(
- request_type=entity_type.ExportEntityTypesRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_entity_types(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- entity_type.ExportEntityTypesRequest,
- dict,
- ],
-)
-def test_export_entity_types_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_entity_types(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_entity_types_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.EntityTypesRestInterceptor, "post_export_entity_types"
- ) as post, mock.patch.object(
- transports.EntityTypesRestInterceptor, "pre_export_entity_types"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = entity_type.ExportEntityTypesRequest.pb(
- entity_type.ExportEntityTypesRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = entity_type.ExportEntityTypesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.export_entity_types(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_import_entity_types_rest_bad_request(
- request_type=entity_type.ImportEntityTypesRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.import_entity_types(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- entity_type.ImportEntityTypesRequest,
- dict,
- ],
-)
-def test_import_entity_types_rest_call_success(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.import_entity_types(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_import_entity_types_rest_interceptors(null_interceptor):
- transport = transports.EntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EntityTypesRestInterceptor(),
- )
- client = EntityTypesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -6396,286 +6237,54 @@ def test_import_entity_types_rest_interceptors(null_interceptor):
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = entity_type.ImportEntityTypesRequest.pb(
- entity_type.ImportEntityTypesRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = entity_type.ImportEntityTypesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.import_entity_types(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ pb_message = entity_type.ImportEntityTypesRequest.pb(
+ entity_type.ImportEntityTypesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- req.return_value = response_value
+ request = entity_type.ImportEntityTypesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- response = client.get_operation(request)
+ client.import_entity_types(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_import_entity_types_rest_bad_request(
+ transport: str = "rest", request_type=entity_type.ImportEntityTypesRequest
):
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -6683,222 +6292,122 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ client.import_entity_types(request)
-def test_initialize_client_w_rest():
+def test_import_entity_types_rest_error():
client = EntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_entity_type_empty_call_rest():
- client = EntityTypesClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call:
- client.get_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.GetEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_entity_type_empty_call_rest():
- client = EntityTypesClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = EntityTypesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_entity_type), "__call__"
- ) as call:
- client.create_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.CreateEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_entity_type_empty_call_rest():
- client = EntityTypesClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = EntityTypesClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_entity_type), "__call__"
- ) as call:
- client.update_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_entity_type.UpdateEntityTypeRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = EntityTypesClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_entity_type_empty_call_rest():
- client = EntityTypesClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_entity_type), "__call__"
- ) as call:
- client.delete_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.DeleteEntityTypeRequest()
-
- assert args[0] == request_msg
+ with pytest.raises(ValueError):
+ client = EntityTypesClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_entity_types_empty_call_rest():
- client = EntityTypesClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_entity_types), "__call__"
- ) as call:
- client.list_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ListEntityTypesRequest()
-
- assert args[0] == request_msg
+ client = EntityTypesClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_entity_types_empty_call_rest():
- client = EntityTypesClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EntityTypesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_entity_types), "__call__"
- ) as call:
- client.export_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ExportEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_entity_types_empty_call_rest():
- client = EntityTypesClient(
+ transport = transports.EntityTypesGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_entity_types), "__call__"
- ) as call:
- client.import_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = entity_type.ImportEntityTypesRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EntityTypesGrpcTransport,
+ transports.EntityTypesGrpcAsyncIOTransport,
+ transports.EntityTypesRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_entity_types_rest_lro_client():
- client = EntityTypesClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = EntityTypesClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -7144,15 +6653,32 @@ def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class
)
-def test_entity_types_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.EntityTypesRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_entity_types_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.EntityTypesRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_entity_types_rest_lro_client():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -7437,115 +6963,415 @@ def test_parse_common_billing_account_path():
}
path = EntityTypesClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = EntityTypesClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = EntityTypesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = EntityTypesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = EntityTypesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EntityTypesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = EntityTypesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = EntityTypesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EntityTypesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = EntityTypesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = EntityTypesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EntityTypesClient.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 = EntityTypesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = EntityTypesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EntityTypesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.EntityTypesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.EntityTypesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = EntityTypesClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = EntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = EntityTypesClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = EntityTypesClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = EntityTypesClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = EntityTypesClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = EntityTypesClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = EntityTypesClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = EntityTypesClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = EntityTypesClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = EntityTypesClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = EntityTypesClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = EntityTypesClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = EntityTypesClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.EntityTypesTransport, "_prep_wrapped_messages"
- ) as prep:
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.EntityTypesTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = EntityTypesClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -7575,7 +7401,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7628,7 +7454,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7673,7 +7499,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -7714,7 +7540,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7769,7 +7595,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7816,7 +7642,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -7859,7 +7685,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7914,7 +7740,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7961,7 +7787,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -8004,7 +7830,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8059,7 +7885,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -8106,7 +7932,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8149,7 +7975,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8201,7 +8027,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = EntityTypesAsyncClient(credentials=async_anonymous_credentials())
+ client = EntityTypesAsyncClient(credentials=ga_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.
@@ -8247,7 +8073,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8263,41 +8089,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = EntityTypesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = EntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = EntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py
index 9e7414e44ef4..0f950c851cba 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -64,8 +46,16 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.environments import (
EnvironmentsAsyncClient,
@@ -78,24 +68,10 @@
from google.cloud.dialogflowcx_v3beta1.types import webhook
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1175,6 +1151,27 @@ def test_list_environments(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_environments_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_environments), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_environments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.ListEnvironmentsRequest()
+
+
def test_list_environments_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1244,6 +1241,31 @@ def test_list_environments_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_environments_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_environments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ environment.ListEnvironmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_environments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.ListEnvironmentsRequest()
+
+
@pytest.mark.asyncio
async def test_list_environments_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1252,7 +1274,7 @@ async def test_list_environments_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1267,23 +1289,27 @@ async def test_list_environments_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_environments
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_environments(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_environments(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1291,7 +1317,7 @@ async def test_list_environments_async(
transport: str = "grpc_asyncio", request_type=environment.ListEnvironmentsRequest
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1361,7 +1387,7 @@ def test_list_environments_field_headers():
@pytest.mark.asyncio
async def test_list_environments_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1435,7 +1461,7 @@ def test_list_environments_flattened_error():
@pytest.mark.asyncio
async def test_list_environments_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1466,7 +1492,7 @@ async def test_list_environments_flattened_async():
@pytest.mark.asyncio
async def test_list_environments_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1518,16 +1544,12 @@ def test_list_environments_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_environments(request={}, retry=retry, timeout=timeout)
+ pager = client.list_environments(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1580,7 +1602,7 @@ def test_list_environments_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_environments_async_pager():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1632,7 +1654,7 @@ async def test_list_environments_async_pager():
@pytest.mark.asyncio
async def test_list_environments_async_pages():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1720,6 +1742,25 @@ def test_get_environment(request_type, transport: str = "grpc"):
assert response.description == "description_value"
+def test_get_environment_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_environment), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.GetEnvironmentRequest()
+
+
def test_get_environment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1783,6 +1824,31 @@ def test_get_environment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_environment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_environment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ environment.Environment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ )
+ )
+ response = await client.get_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.GetEnvironmentRequest()
+
+
@pytest.mark.asyncio
async def test_get_environment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1791,7 +1857,7 @@ async def test_get_environment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1806,23 +1872,27 @@ async def test_get_environment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_environment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_environment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1830,7 +1900,7 @@ async def test_get_environment_async(
transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1900,7 +1970,7 @@ def test_get_environment_field_headers():
@pytest.mark.asyncio
async def test_get_environment_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1970,7 +2040,7 @@ def test_get_environment_flattened_error():
@pytest.mark.asyncio
async def test_get_environment_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1999,7 +2069,7 @@ async def test_get_environment_flattened_async():
@pytest.mark.asyncio
async def test_get_environment_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2046,6 +2116,27 @@ def test_create_environment(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_create_environment_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_environment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_environment.CreateEnvironmentRequest()
+
+
def test_create_environment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2108,9 +2199,8 @@ def test_create_environment_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.create_environment(request)
@@ -2120,6 +2210,29 @@ def test_create_environment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_environment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_environment), "__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_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_environment.CreateEnvironmentRequest()
+
+
@pytest.mark.asyncio
async def test_create_environment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2128,7 +2241,7 @@ async def test_create_environment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2143,28 +2256,31 @@ async def test_create_environment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_environment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_environment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.create_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2173,7 +2289,7 @@ async def test_create_environment_async(
request_type=gcdc_environment.CreateEnvironmentRequest,
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2240,7 +2356,7 @@ def test_create_environment_field_headers():
@pytest.mark.asyncio
async def test_create_environment_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2319,7 +2435,7 @@ def test_create_environment_flattened_error():
@pytest.mark.asyncio
async def test_create_environment_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2354,7 +2470,7 @@ async def test_create_environment_flattened_async():
@pytest.mark.asyncio
async def test_create_environment_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2402,6 +2518,27 @@ def test_update_environment(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_update_environment_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_environment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_environment.UpdateEnvironmentRequest()
+
+
def test_update_environment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2460,9 +2597,8 @@ def test_update_environment_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.update_environment(request)
@@ -2472,6 +2608,29 @@ def test_update_environment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_environment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_environment), "__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_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_environment.UpdateEnvironmentRequest()
+
+
@pytest.mark.asyncio
async def test_update_environment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2480,7 +2639,7 @@ async def test_update_environment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2495,28 +2654,31 @@ async def test_update_environment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_environment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_environment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.update_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2525,7 +2687,7 @@ async def test_update_environment_async(
request_type=gcdc_environment.UpdateEnvironmentRequest,
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2592,7 +2754,7 @@ def test_update_environment_field_headers():
@pytest.mark.asyncio
async def test_update_environment_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2671,7 +2833,7 @@ def test_update_environment_flattened_error():
@pytest.mark.asyncio
async def test_update_environment_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2706,7 +2868,7 @@ async def test_update_environment_flattened_async():
@pytest.mark.asyncio
async def test_update_environment_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2754,6 +2916,27 @@ def test_delete_environment(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_environment_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_environment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.DeleteEnvironmentRequest()
+
+
def test_delete_environment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2823,6 +3006,27 @@ def test_delete_environment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_environment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_environment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_environment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.DeleteEnvironmentRequest()
+
+
@pytest.mark.asyncio
async def test_delete_environment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2831,7 +3035,7 @@ async def test_delete_environment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2846,23 +3050,27 @@ async def test_delete_environment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_environment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_environment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2870,7 +3078,7 @@ async def test_delete_environment_async(
transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2935,7 +3143,7 @@ def test_delete_environment_field_headers():
@pytest.mark.asyncio
async def test_delete_environment_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3007,7 +3215,7 @@ def test_delete_environment_flattened_error():
@pytest.mark.asyncio
async def test_delete_environment_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3036,7 +3244,7 @@ async def test_delete_environment_flattened_async():
@pytest.mark.asyncio
async def test_delete_environment_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3086,15 +3294,36 @@ def test_lookup_environment_history(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
-def test_lookup_environment_history_non_empty_request_with_auto_populated_field():
- # This test is a coverage failsafe to make sure that UUID4 fields are
- # automatically populated, according to AIP-4235, with non-empty requests.
+def test_lookup_environment_history_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 = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
- # Populate all string fields in the request which are not UUID4
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.lookup_environment_history), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.lookup_environment_history()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.LookupEnvironmentHistoryRequest()
+
+
+def test_lookup_environment_history_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
# since we want to check that UUID4 are populated automatically
# if they meet the requirements of AIP 4235.
request = environment.LookupEnvironmentHistoryRequest(
@@ -3158,6 +3387,31 @@ def test_lookup_environment_history_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_lookup_environment_history_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.lookup_environment_history), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ environment.LookupEnvironmentHistoryResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.lookup_environment_history()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.LookupEnvironmentHistoryRequest()
+
+
@pytest.mark.asyncio
async def test_lookup_environment_history_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3166,7 +3420,7 @@ async def test_lookup_environment_history_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3181,23 +3435,27 @@ async def test_lookup_environment_history_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.lookup_environment_history
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.lookup_environment_history(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.lookup_environment_history(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3206,7 +3464,7 @@ async def test_lookup_environment_history_async(
request_type=environment.LookupEnvironmentHistoryRequest,
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3276,7 +3534,7 @@ def test_lookup_environment_history_field_headers():
@pytest.mark.asyncio
async def test_lookup_environment_history_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3350,7 +3608,7 @@ def test_lookup_environment_history_flattened_error():
@pytest.mark.asyncio
async def test_lookup_environment_history_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3381,7 +3639,7 @@ async def test_lookup_environment_history_flattened_async():
@pytest.mark.asyncio
async def test_lookup_environment_history_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3433,18 +3691,12 @@ def test_lookup_environment_history_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", ""),)),
)
- pager = client.lookup_environment_history(
- request={}, retry=retry, timeout=timeout
- )
+ pager = client.lookup_environment_history(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -3497,7 +3749,7 @@ def test_lookup_environment_history_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_lookup_environment_history_async_pager():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3549,7 +3801,7 @@ async def test_lookup_environment_history_async_pager():
@pytest.mark.asyncio
async def test_lookup_environment_history_async_pages():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3632,6 +3884,27 @@ def test_run_continuous_test(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_run_continuous_test_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.run_continuous_test), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.run_continuous_test()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.RunContinuousTestRequest()
+
+
def test_run_continuous_test_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3694,9 +3967,8 @@ def test_run_continuous_test_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.run_continuous_test(request)
@@ -3706,6 +3978,29 @@ def test_run_continuous_test_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_run_continuous_test_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.run_continuous_test), "__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.run_continuous_test()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.RunContinuousTestRequest()
+
+
@pytest.mark.asyncio
async def test_run_continuous_test_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3714,7 +4009,7 @@ async def test_run_continuous_test_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3729,28 +4024,31 @@ async def test_run_continuous_test_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.run_continuous_test
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.run_continuous_test(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.run_continuous_test(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3758,7 +4056,7 @@ async def test_run_continuous_test_async(
transport: str = "grpc_asyncio", request_type=environment.RunContinuousTestRequest
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3825,7 +4123,7 @@ def test_run_continuous_test_field_headers():
@pytest.mark.asyncio
async def test_run_continuous_test_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3894,6 +4192,27 @@ def test_list_continuous_test_results(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_continuous_test_results_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_continuous_test_results), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_continuous_test_results()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.ListContinuousTestResultsRequest()
+
+
def test_list_continuous_test_results_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3966,6 +4285,31 @@ def test_list_continuous_test_results_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_continuous_test_results_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_continuous_test_results), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ environment.ListContinuousTestResultsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_continuous_test_results()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.ListContinuousTestResultsRequest()
+
+
@pytest.mark.asyncio
async def test_list_continuous_test_results_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3974,7 +4318,7 @@ async def test_list_continuous_test_results_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3989,23 +4333,27 @@ async def test_list_continuous_test_results_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_continuous_test_results
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_continuous_test_results(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_continuous_test_results(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4014,7 +4362,7 @@ async def test_list_continuous_test_results_async(
request_type=environment.ListContinuousTestResultsRequest,
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4084,7 +4432,7 @@ def test_list_continuous_test_results_field_headers():
@pytest.mark.asyncio
async def test_list_continuous_test_results_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4158,7 +4506,7 @@ def test_list_continuous_test_results_flattened_error():
@pytest.mark.asyncio
async def test_list_continuous_test_results_flattened_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4189,7 +4537,7 @@ async def test_list_continuous_test_results_flattened_async():
@pytest.mark.asyncio
async def test_list_continuous_test_results_flattened_error_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4241,18 +4589,12 @@ def test_list_continuous_test_results_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_continuous_test_results(
- request={}, retry=retry, timeout=timeout
- )
+ pager = client.list_continuous_test_results(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -4305,7 +4647,7 @@ def test_list_continuous_test_results_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_continuous_test_results_async_pager():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4357,7 +4699,7 @@ async def test_list_continuous_test_results_async_pager():
@pytest.mark.asyncio
async def test_list_continuous_test_results_async_pages():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4438,6 +4780,25 @@ def test_deploy_flow(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_deploy_flow_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 = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.deploy_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.DeployFlowRequest()
+
+
def test_deploy_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4496,9 +4857,8 @@ def test_deploy_flow_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.deploy_flow(request)
@@ -4508,6 +4868,27 @@ def test_deploy_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_deploy_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.deploy_flow), "__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.deploy_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == environment.DeployFlowRequest()
+
+
@pytest.mark.asyncio
async def test_deploy_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4516,7 +4897,7 @@ async def test_deploy_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4531,28 +4912,31 @@ async def test_deploy_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.deploy_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.deploy_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.deploy_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4560,7 +4944,7 @@ async def test_deploy_flow_async(
transport: str = "grpc_asyncio", request_type=environment.DeployFlowRequest
):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4623,7 +5007,7 @@ def test_deploy_flow_field_headers():
@pytest.mark.asyncio
async def test_deploy_flow_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4652,6 +5036,46 @@ async def test_deploy_flow_field_headers_async():
) in kw["metadata"]
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ environment.ListEnvironmentsRequest,
+ dict,
+ ],
+)
+def test_list_environments_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = environment.ListEnvironmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.ListEnvironmentsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_environments(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListEnvironmentsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_environments_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4788,13 +5212,94 @@ def test_list_environments_rest_unset_required_fields():
)
-def test_list_environments_rest_flattened():
- client = EnvironmentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_environments_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_list_environments"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_list_environments"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = environment.ListEnvironmentsRequest.pb(
+ environment.ListEnvironmentsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = environment.ListEnvironmentsResponse.to_json(
+ environment.ListEnvironmentsResponse()
+ )
+
+ request = environment.ListEnvironmentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = environment.ListEnvironmentsResponse()
+
+ client.list_environments(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_environments_rest_bad_request(
+ transport: str = "rest", request_type=environment.ListEnvironmentsRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_environments(request)
+
+
+def test_list_environments_rest_flattened():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
return_value = environment.ListEnvironmentsResponse()
@@ -4908,6 +5413,52 @@ def test_list_environments_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ environment.GetEnvironmentRequest,
+ dict,
+ ],
+)
+def test_get_environment_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = environment.Environment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.Environment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_environment(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, environment.Environment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+
+
def test_get_environment_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5027,6 +5578,89 @@ def test_get_environment_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_environment_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
+ )
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_get_environment"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_get_environment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = environment.GetEnvironmentRequest.pb(
+ environment.GetEnvironmentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = environment.Environment.to_json(
+ environment.Environment()
+ )
+
+ request = environment.GetEnvironmentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = environment.Environment()
+
+ client.get_environment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_environment_rest_bad_request(
+ transport: str = "rest", request_type=environment.GetEnvironmentRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_environment(request)
+
+
def test_get_environment_rest_flattened():
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5086,197 +5720,162 @@ def test_get_environment_rest_flattened_error(transport: str = "rest"):
)
-def test_create_environment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.create_environment in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.create_environment
- ] = mock_rpc
-
- request = {}
- client.create_environment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.create_environment(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_create_environment_rest_required_fields(
- request_type=gcdc_environment.CreateEnvironmentRequest,
-):
- transport_class = transports.EnvironmentsRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+def test_get_environment_rest_error():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_environment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
- jsonified_request["parent"] = "parent_value"
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_environment.CreateEnvironmentRequest,
+ dict,
+ ],
+)
+def test_create_environment_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_environment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["environment"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "version_configs": [{"version": "version_value"}],
+ "update_time": {"seconds": 751, "nanos": 543},
+ "test_cases_config": {
+ "test_cases": ["test_cases_value1", "test_cases_value2"],
+ "enable_continuous_run": True,
+ "enable_predeployment_run": True,
+ },
+ "webhook_config": {
+ "webhook_overrides": [
+ {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "generic_web_service": {
+ "uri": "uri_value",
+ "username": "username_value",
+ "password": "password_value",
+ "request_headers": {},
+ "allowed_ca_certs": [
+ b"allowed_ca_certs_blob1",
+ b"allowed_ca_certs_blob2",
+ ],
+ "oauth_config": {
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ "scopes": ["scopes_value1", "scopes_value2"],
+ },
+ "service_agent_auth": 1,
+ "webhook_type": 1,
+ "http_method": 1,
+ "request_body": "request_body_value",
+ "parameter_mapping": {},
+ },
+ "service_directory": {
+ "service": "service_value",
+ "generic_web_service": {},
+ },
+ "timeout": {"seconds": 751, "nanos": 543},
+ "disabled": True,
+ }
+ ]
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_environment.CreateEnvironmentRequest.meta.fields["environment"]
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
- response = client.create_environment(request)
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
-def test_create_environment_rest_unset_required_fields():
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ subfields_not_in_runtime = []
- unset_fields = transport.create_environment._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "parent",
- "environment",
- )
- )
- )
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["environment"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
-def test_create_environment_rest_flattened():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["environment"][field])):
+ del request_init["environment"][field][i][subfield]
+ else:
+ del request_init["environment"][field][subfield]
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
return_value = operations_pb2.Operation(name="operations/spam")
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- environment=gcdc_environment.Environment(name="name_value"),
- )
- mock_args.update(sample_request)
-
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
+
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
+ response = client.create_environment(request)
- client.create_environment(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/environments"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_environment_rest_flattened_error(transport: str = "rest"):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_environment(
- gcdc_environment.CreateEnvironmentRequest(),
- parent="parent_value",
- environment=gcdc_environment.Environment(name="name_value"),
- )
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
-def test_update_environment_rest_use_cached_wrapped_rpc():
+def test_create_environment_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -5291,7 +5890,7 @@ def test_update_environment_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.update_environment in client._transport._wrapped_methods
+ client._transport.create_environment in client._transport._wrapped_methods
)
# Replace cached wrapped function with mock
@@ -5300,11 +5899,11 @@ def test_update_environment_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.update_environment
+ client._transport.create_environment
] = mock_rpc
request = {}
- client.update_environment(request)
+ client.create_environment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
@@ -5313,19 +5912,20 @@ def test_update_environment_rest_use_cached_wrapped_rpc():
# subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
- client.update_environment(request)
+ client.create_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_update_environment_rest_required_fields(
- request_type=gcdc_environment.UpdateEnvironmentRequest,
+def test_create_environment_rest_required_fields(
+ request_type=gcdc_environment.CreateEnvironmentRequest,
):
transport_class = transports.EnvironmentsRestTransport
request_init = {}
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5336,19 +5936,21 @@ def test_update_environment_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_environment._get_unset_required_fields(jsonified_request)
+ ).create_environment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ jsonified_request["parent"] = "parent_value"
+
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_environment._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
+ ).create_environment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5369,7 +5971,7 @@ def test_update_environment_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "patch",
+ "method": "post",
"query_params": pb_request,
}
transcode_result["body"] = pb_request
@@ -5382,212 +5984,114 @@ def test_update_environment_rest_required_fields(
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.update_environment(request)
+ response = client.create_environment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_update_environment_rest_unset_required_fields():
+def test_create_environment_rest_unset_required_fields():
transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.update_environment._get_unset_required_fields({})
+ unset_fields = transport.create_environment._get_unset_required_fields({})
assert set(unset_fields) == (
- set(("updateMask",))
+ set(())
& set(
(
+ "parent",
"environment",
- "updateMask",
)
)
)
-def test_update_environment_rest_flattened():
- client = EnvironmentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_environment_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "environment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- environment=gcdc_environment.Environment(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_environment(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{environment.name=projects/*/locations/*/agents/*/environments/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_environment_rest_flattened_error(transport: str = "rest"):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_environment(
- gcdc_environment.UpdateEnvironmentRequest(),
- environment=gcdc_environment.Environment(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_create_environment"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_create_environment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_environment.CreateEnvironmentRequest.pb(
+ gcdc_environment.CreateEnvironmentRequest()
)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
-
-def test_delete_environment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.delete_environment in client._transport._wrapped_methods
- )
+ request = gcdc_environment.CreateEnvironmentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.create_environment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[
- client._transport.delete_environment
- ] = mock_rpc
-
- request = {}
- client.delete_environment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.delete_environment(request)
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_delete_environment_rest_required_fields(
- request_type=environment.DeleteEnvironmentRequest,
+def test_create_environment_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_environment.CreateEnvironmentRequest
):
- transport_class = transports.EnvironmentsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_environment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_environment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = None
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "delete",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.delete_environment(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-def test_delete_environment_rest_unset_required_fields():
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
- unset_fields = transport.delete_environment._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_environment(request)
-def test_delete_environment_rest_flattened():
+def test_create_environment_rest_flattened():
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -5596,40 +6100,39 @@ def test_delete_environment_rest_flattened():
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = operations_pb2.Operation(name="operations/spam")
# get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
# get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ parent="parent_value",
+ environment=gcdc_environment.Environment(name="name_value"),
)
mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.delete_environment(**mock_args)
+ client.create_environment(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}"
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/environments"
% client.transport._host,
args[1],
)
-def test_delete_environment_rest_flattened_error(transport: str = "rest"):
+def test_create_environment_rest_flattened_error(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5638,30 +6141,189 @@ def test_delete_environment_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.delete_environment(
- environment.DeleteEnvironmentRequest(),
- name="name_value",
+ client.create_environment(
+ gcdc_environment.CreateEnvironmentRequest(),
+ parent="parent_value",
+ environment=gcdc_environment.Environment(name="name_value"),
)
-def test_lookup_environment_history_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_create_environment_rest_error():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
- # Ensure method has been cached
- assert (
- client._transport.lookup_environment_history
- in client._transport._wrapped_methods
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_environment.UpdateEnvironmentRequest,
+ dict,
+ ],
+)
+def test_update_environment_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "environment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ }
+ request_init["environment"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "version_configs": [{"version": "version_value"}],
+ "update_time": {"seconds": 751, "nanos": 543},
+ "test_cases_config": {
+ "test_cases": ["test_cases_value1", "test_cases_value2"],
+ "enable_continuous_run": True,
+ "enable_predeployment_run": True,
+ },
+ "webhook_config": {
+ "webhook_overrides": [
+ {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "generic_web_service": {
+ "uri": "uri_value",
+ "username": "username_value",
+ "password": "password_value",
+ "request_headers": {},
+ "allowed_ca_certs": [
+ b"allowed_ca_certs_blob1",
+ b"allowed_ca_certs_blob2",
+ ],
+ "oauth_config": {
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ "scopes": ["scopes_value1", "scopes_value2"],
+ },
+ "service_agent_auth": 1,
+ "webhook_type": 1,
+ "http_method": 1,
+ "request_body": "request_body_value",
+ "parameter_mapping": {},
+ },
+ "service_directory": {
+ "service": "service_value",
+ "generic_web_service": {},
+ },
+ "timeout": {"seconds": 751, "nanos": 543},
+ "disabled": True,
+ }
+ ]
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_environment.UpdateEnvironmentRequest.meta.fields["environment"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["environment"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["environment"][field])):
+ del request_init["environment"][field][i][subfield]
+ else:
+ del request_init["environment"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_environment(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_update_environment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_environment in client._transport._wrapped_methods
+ )
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
@@ -5669,29 +6331,32 @@ def test_lookup_environment_history_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.lookup_environment_history
+ client._transport.update_environment
] = mock_rpc
request = {}
- client.lookup_environment_history(request)
+ client.update_environment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.lookup_environment_history(request)
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.update_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_lookup_environment_history_rest_required_fields(
- request_type=environment.LookupEnvironmentHistoryRequest,
+def test_update_environment_rest_required_fields(
+ request_type=gcdc_environment.UpdateEnvironmentRequest,
):
transport_class = transports.EnvironmentsRestTransport
request_init = {}
- request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5702,28 +6367,19 @@ def test_lookup_environment_history_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).lookup_environment_history._get_unset_required_fields(jsonified_request)
+ ).update_environment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
-
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).lookup_environment_history._get_unset_required_fields(jsonified_request)
+ ).update_environment._get_unset_required_fields(jsonified_request)
# Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "page_size",
- "page_token",
- )
- )
+ assert not set(unset_fields) - set(("update_mask",))
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5732,7 +6388,7 @@ def test_lookup_environment_history_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = environment.LookupEnvironmentHistoryResponse()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -5744,90 +6400,176 @@ def test_lookup_environment_history_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "get",
+ "method": "patch",
"query_params": pb_request,
}
+ transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.lookup_environment_history(request)
+ response = client.update_environment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_lookup_environment_history_rest_unset_required_fields():
+def test_update_environment_rest_unset_required_fields():
transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.lookup_environment_history._get_unset_required_fields({})
+ unset_fields = transport.update_environment._get_unset_required_fields({})
assert set(unset_fields) == (
- set(
+ set(("updateMask",))
+ & set(
(
- "pageSize",
- "pageToken",
+ "environment",
+ "updateMask",
)
)
- & set(("name",))
)
-def test_lookup_environment_history_rest_flattened():
- client = EnvironmentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_environment_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_update_environment"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_update_environment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_environment.UpdateEnvironmentRequest.pb(
+ gcdc_environment.UpdateEnvironmentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.LookupEnvironmentHistoryResponse()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
+
+ request = gcdc_environment.UpdateEnvironmentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
+
+ client.update_environment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_environment_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_environment.UpdateEnvironmentRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "environment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_environment(request)
+
+
+def test_update_environment_rest_flattened():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
# get arguments that satisfy an http rule for this method
sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ "environment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
}
# get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ environment=gcdc_environment.Environment(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.lookup_environment_history(**mock_args)
+ client.update_environment(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}:lookupEnvironmentHistory"
+ "%s/v3beta1/{environment.name=projects/*/locations/*/agents/*/environments/*}"
% client.transport._host,
args[1],
)
-def test_lookup_environment_history_rest_flattened_error(transport: str = "rest"):
+def test_update_environment_rest_flattened_error(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5836,78 +6578,57 @@ def test_lookup_environment_history_rest_flattened_error(transport: str = "rest"
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.lookup_environment_history(
- environment.LookupEnvironmentHistoryRequest(),
- name="name_value",
+ client.update_environment(
+ gcdc_environment.UpdateEnvironmentRequest(),
+ environment=gcdc_environment.Environment(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
-def test_lookup_environment_history_rest_pager(transport: str = "rest"):
+def test_update_environment_rest_error():
client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- environment.LookupEnvironmentHistoryResponse(
- environments=[
- environment.Environment(),
- environment.Environment(),
- environment.Environment(),
- ],
- next_page_token="abc",
- ),
- environment.LookupEnvironmentHistoryResponse(
- environments=[],
- next_page_token="def",
- ),
- environment.LookupEnvironmentHistoryResponse(
- environments=[
- environment.Environment(),
- ],
- next_page_token="ghi",
- ),
- environment.LookupEnvironmentHistoryResponse(
- environments=[
- environment.Environment(),
- environment.Environment(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
- # Wrap the values into proper Response objs
- response = tuple(
- environment.LookupEnvironmentHistoryResponse.to_json(x) for x in response
- )
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ environment.DeleteEnvironmentRequest,
+ dict,
+ ],
+)
+def test_delete_environment_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
- pager = client.lookup_environment_history(request=sample_request)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, environment.Environment) for i in results)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- pages = list(client.lookup_environment_history(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_environment(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_run_continuous_test_rest_use_cached_wrapped_rpc():
+def test_delete_environment_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -5922,7 +6643,7 @@ def test_run_continuous_test_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.run_continuous_test in client._transport._wrapped_methods
+ client._transport.delete_environment in client._transport._wrapped_methods
)
# Replace cached wrapped function with mock
@@ -5931,33 +6652,29 @@ def test_run_continuous_test_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.run_continuous_test
+ client._transport.delete_environment
] = mock_rpc
request = {}
- client.run_continuous_test(request)
+ client.delete_environment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.run_continuous_test(request)
+ client.delete_environment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_run_continuous_test_rest_required_fields(
- request_type=environment.RunContinuousTestRequest,
+def test_delete_environment_rest_required_fields(
+ request_type=environment.DeleteEnvironmentRequest,
):
transport_class = transports.EnvironmentsRestTransport
request_init = {}
- request_init["environment"] = ""
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5968,21 +6685,21 @@ def test_run_continuous_test_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).run_continuous_test._get_unset_required_fields(jsonified_request)
+ ).delete_environment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["environment"] = "environment_value"
+ jsonified_request["name"] = "name_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).run_continuous_test._get_unset_required_fields(jsonified_request)
+ ).delete_environment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "environment" in jsonified_request
- assert jsonified_request["environment"] == "environment_value"
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5991,7 +6708,7 @@ def test_run_continuous_test_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6003,53 +6720,232 @@ def test_run_continuous_test_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "post",
+ "method": "delete",
"query_params": pb_request,
}
- transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
+ json_return_value = ""
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.run_continuous_test(request)
+ response = client.delete_environment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_run_continuous_test_rest_unset_required_fields():
+def test_delete_environment_rest_unset_required_fields():
transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.run_continuous_test._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("environment",)))
+ unset_fields = transport.delete_environment._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-def test_list_continuous_test_results_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_environment_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
+ )
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_delete_environment"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = environment.DeleteEnvironmentRequest.pb(
+ environment.DeleteEnvironmentRequest()
)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.list_continuous_test_results
- in client._transport._wrapped_methods
- )
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = environment.DeleteEnvironmentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_environment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_environment_rest_bad_request(
+ transport: str = "rest", request_type=environment.DeleteEnvironmentRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_environment(request)
+
+
+def test_delete_environment_rest_flattened():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.delete_environment(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_environment_rest_flattened_error(transport: str = "rest"):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_environment(
+ environment.DeleteEnvironmentRequest(),
+ name="name_value",
+ )
+
+
+def test_delete_environment_rest_error():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ environment.LookupEnvironmentHistoryRequest,
+ dict,
+ ],
+)
+def test_lookup_environment_history_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = environment.LookupEnvironmentHistoryResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.lookup_environment_history(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.LookupEnvironmentHistoryPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_lookup_environment_history_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.lookup_environment_history
+ in client._transport._wrapped_methods
+ )
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
@@ -6057,29 +6953,29 @@ def test_list_continuous_test_results_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.list_continuous_test_results
+ client._transport.lookup_environment_history
] = mock_rpc
request = {}
- client.list_continuous_test_results(request)
+ client.lookup_environment_history(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.list_continuous_test_results(request)
+ client.lookup_environment_history(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_list_continuous_test_results_rest_required_fields(
- request_type=environment.ListContinuousTestResultsRequest,
+def test_lookup_environment_history_rest_required_fields(
+ request_type=environment.LookupEnvironmentHistoryRequest,
):
transport_class = transports.EnvironmentsRestTransport
request_init = {}
- request_init["parent"] = ""
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -6090,16 +6986,16 @@ def test_list_continuous_test_results_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).list_continuous_test_results._get_unset_required_fields(jsonified_request)
+ ).lookup_environment_history._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["parent"] = "parent_value"
+ jsonified_request["name"] = "name_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).list_continuous_test_results._get_unset_required_fields(jsonified_request)
+ ).lookup_environment_history._get_unset_required_fields(jsonified_request)
# Check that path parameters and body parameters are not mixing in.
assert not set(unset_fields) - set(
(
@@ -6110,8 +7006,8 @@ def test_list_continuous_test_results_rest_required_fields(
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6120,7 +7016,7 @@ def test_list_continuous_test_results_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = environment.ListContinuousTestResultsResponse()
+ return_value = environment.LookupEnvironmentHistoryResponse()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6141,27 +7037,25 @@ def test_list_continuous_test_results_rest_required_fields(
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = environment.ListContinuousTestResultsResponse.pb(
- return_value
- )
+ return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_continuous_test_results(request)
+ response = client.lookup_environment_history(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_list_continuous_test_results_rest_unset_required_fields():
+def test_lookup_environment_history_rest_unset_required_fields():
transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.list_continuous_test_results._get_unset_required_fields({})
+ unset_fields = transport.lookup_environment_history._get_unset_required_fields({})
assert set(unset_fields) == (
set(
(
@@ -6169,55 +7063,140 @@ def test_list_continuous_test_results_rest_unset_required_fields():
"pageToken",
)
)
- & set(("parent",))
+ & set(("name",))
)
-def test_list_continuous_test_results_rest_flattened():
- client = EnvironmentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_lookup_environment_history_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.ListContinuousTestResultsResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_lookup_environment_history"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_lookup_environment_history"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = environment.LookupEnvironmentHistoryRequest.pb(
+ environment.LookupEnvironmentHistoryRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ environment.LookupEnvironmentHistoryResponse.to_json(
+ environment.LookupEnvironmentHistoryResponse()
+ )
)
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = environment.ListContinuousTestResultsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.list_continuous_test_results(**mock_args)
+
+ request = environment.LookupEnvironmentHistoryRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = environment.LookupEnvironmentHistoryResponse()
+
+ client.lookup_environment_history(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_lookup_environment_history_rest_bad_request(
+ transport: str = "rest", request_type=environment.LookupEnvironmentHistoryRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.lookup_environment_history(request)
+
+
+def test_lookup_environment_history_rest_flattened():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = environment.LookupEnvironmentHistoryResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.lookup_environment_history(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/continuousTestResults"
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*}:lookupEnvironmentHistory"
% client.transport._host,
args[1],
)
-def test_list_continuous_test_results_rest_flattened_error(transport: str = "rest"):
+def test_lookup_environment_history_rest_flattened_error(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -6226,13 +7205,13 @@ def test_list_continuous_test_results_rest_flattened_error(transport: str = "res
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.list_continuous_test_results(
- environment.ListContinuousTestResultsRequest(),
- parent="parent_value",
+ client.lookup_environment_history(
+ environment.LookupEnvironmentHistoryRequest(),
+ name="name_value",
)
-def test_list_continuous_test_results_rest_pager(transport: str = "rest"):
+def test_lookup_environment_history_rest_pager(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -6244,28 +7223,28 @@ def test_list_continuous_test_results_rest_pager(transport: str = "rest"):
# with mock.patch.object(path_template, 'transcode') as transcode:
# Set the response as a series of pages
response = (
- environment.ListContinuousTestResultsResponse(
- continuous_test_results=[
- environment.ContinuousTestResult(),
- environment.ContinuousTestResult(),
- environment.ContinuousTestResult(),
+ environment.LookupEnvironmentHistoryResponse(
+ environments=[
+ environment.Environment(),
+ environment.Environment(),
+ environment.Environment(),
],
next_page_token="abc",
),
- environment.ListContinuousTestResultsResponse(
- continuous_test_results=[],
+ environment.LookupEnvironmentHistoryResponse(
+ environments=[],
next_page_token="def",
),
- environment.ListContinuousTestResultsResponse(
- continuous_test_results=[
- environment.ContinuousTestResult(),
+ environment.LookupEnvironmentHistoryResponse(
+ environments=[
+ environment.Environment(),
],
next_page_token="ghi",
),
- environment.ListContinuousTestResultsResponse(
- continuous_test_results=[
- environment.ContinuousTestResult(),
- environment.ContinuousTestResult(),
+ environment.LookupEnvironmentHistoryResponse(
+ environments=[
+ environment.Environment(),
+ environment.Environment(),
],
),
)
@@ -6274,7 +7253,7 @@ def test_list_continuous_test_results_rest_pager(transport: str = "rest"):
# Wrap the values into proper Response objs
response = tuple(
- environment.ListContinuousTestResultsResponse.to_json(x) for x in response
+ environment.LookupEnvironmentHistoryResponse.to_json(x) for x in response
)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
@@ -6283,21 +7262,58 @@ def test_list_continuous_test_results_rest_pager(transport: str = "rest"):
req.side_effect = return_values
sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
}
- pager = client.list_continuous_test_results(request=sample_request)
+ pager = client.lookup_environment_history(request=sample_request)
results = list(pager)
assert len(results) == 6
- assert all(isinstance(i, environment.ContinuousTestResult) for i in results)
+ assert all(isinstance(i, environment.Environment) for i in results)
- pages = list(client.list_continuous_test_results(request=sample_request).pages)
+ pages = list(client.lookup_environment_history(request=sample_request).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
-def test_deploy_flow_rest_use_cached_wrapped_rpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ environment.RunContinuousTestRequest,
+ dict,
+ ],
+)
+def test_run_continuous_test_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.run_continuous_test(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_run_continuous_test_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -6311,17 +7327,21 @@ def test_deploy_flow_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.deploy_flow in client._transport._wrapped_methods
+ assert (
+ client._transport.run_continuous_test in client._transport._wrapped_methods
+ )
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.deploy_flow] = mock_rpc
+ client._transport._wrapped_methods[
+ client._transport.run_continuous_test
+ ] = mock_rpc
request = {}
- client.deploy_flow(request)
+ client.run_continuous_test(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
@@ -6330,19 +7350,20 @@ def test_deploy_flow_rest_use_cached_wrapped_rpc():
# subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
- client.deploy_flow(request)
+ client.run_continuous_test(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_deploy_flow_rest_required_fields(request_type=environment.DeployFlowRequest):
+def test_run_continuous_test_rest_required_fields(
+ request_type=environment.RunContinuousTestRequest,
+):
transport_class = transports.EnvironmentsRestTransport
request_init = {}
request_init["environment"] = ""
- request_init["flow_version"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -6353,24 +7374,21 @@ def test_deploy_flow_rest_required_fields(request_type=environment.DeployFlowReq
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).deploy_flow._get_unset_required_fields(jsonified_request)
+ ).run_continuous_test._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
jsonified_request["environment"] = "environment_value"
- jsonified_request["flowVersion"] = "flow_version_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).deploy_flow._get_unset_required_fields(jsonified_request)
+ ).run_continuous_test._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
assert "environment" in jsonified_request
assert jsonified_request["environment"] == "environment_value"
- assert "flowVersion" in jsonified_request
- assert jsonified_request["flowVersion"] == "flow_version_value"
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6404,1545 +7422,70 @@ def test_deploy_flow_rest_required_fields(request_type=environment.DeployFlowReq
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.deploy_flow(request)
+ response = client.run_continuous_test(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_deploy_flow_rest_unset_required_fields():
+def test_run_continuous_test_rest_unset_required_fields():
transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.deploy_flow._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "environment",
- "flowVersion",
- )
- )
- )
+ unset_fields = transport.run_continuous_test._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("environment",)))
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.EnvironmentsGrpcTransport(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_run_continuous_test_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
- with pytest.raises(ValueError):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_run_continuous_test"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_run_continuous_test"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = environment.RunContinuousTestRequest.pb(
+ environment.RunContinuousTestRequest()
)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.EnvironmentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EnvironmentsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- # It is an error to provide an api_key and a transport instance.
- transport = transports.EnvironmentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = EnvironmentsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = EnvironmentsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.EnvironmentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EnvironmentsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EnvironmentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = EnvironmentsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EnvironmentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.EnvironmentsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.EnvironmentsGrpcTransport,
- transports.EnvironmentsGrpcAsyncIOTransport,
- transports.EnvironmentsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = EnvironmentsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_environments_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_environments), "__call__"
- ) as call:
- call.return_value = environment.ListEnvironmentsResponse()
- client.list_environments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListEnvironmentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_environment_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_environment), "__call__") as call:
- call.return_value = environment.Environment()
- client.get_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.GetEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_environment_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_environment), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.create_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.CreateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_environment_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_environment), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.update_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.UpdateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_environment_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_environment), "__call__"
- ) as call:
- call.return_value = None
- client.delete_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeleteEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_lookup_environment_history_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.lookup_environment_history), "__call__"
- ) as call:
- call.return_value = environment.LookupEnvironmentHistoryResponse()
- client.lookup_environment_history(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.LookupEnvironmentHistoryRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_run_continuous_test_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.run_continuous_test), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.run_continuous_test(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.RunContinuousTestRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_continuous_test_results_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_continuous_test_results), "__call__"
- ) as call:
- call.return_value = environment.ListContinuousTestResultsResponse()
- client.list_continuous_test_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListContinuousTestResultsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_deploy_flow_empty_call_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.deploy_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeployFlowRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = EnvironmentsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_environments_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_environments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- environment.ListEnvironmentsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_environments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListEnvironmentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_environment_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_environment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- environment.Environment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- )
- )
- await client.get_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.GetEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_environment_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_environment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.create_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.CreateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_environment_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_environment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.update_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.UpdateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_environment_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_environment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeleteEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_lookup_environment_history_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.lookup_environment_history), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- environment.LookupEnvironmentHistoryResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.lookup_environment_history(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.LookupEnvironmentHistoryRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_run_continuous_test_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.run_continuous_test), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.run_continuous_test(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.RunContinuousTestRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_continuous_test_results_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_continuous_test_results), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- environment.ListContinuousTestResultsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_continuous_test_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListContinuousTestResultsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_deploy_flow_empty_call_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.deploy_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeployFlowRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = EnvironmentsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_environments_rest_bad_request(
- request_type=environment.ListEnvironmentsRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_environments(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.ListEnvironmentsRequest,
- dict,
- ],
-)
-def test_list_environments_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.ListEnvironmentsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = environment.ListEnvironmentsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_environments(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListEnvironmentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_environments_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_list_environments"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_list_environments"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = environment.ListEnvironmentsRequest.pb(
- environment.ListEnvironmentsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = environment.ListEnvironmentsResponse.to_json(
- environment.ListEnvironmentsResponse()
- )
- req.return_value.content = return_value
-
- request = environment.ListEnvironmentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = environment.ListEnvironmentsResponse()
-
- client.list_environments(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_environment_rest_bad_request(
- request_type=environment.GetEnvironmentRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_environment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.GetEnvironmentRequest,
- dict,
- ],
-)
-def test_get_environment_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.Environment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = environment.Environment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_environment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, environment.Environment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_environment_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_get_environment"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_get_environment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = environment.GetEnvironmentRequest.pb(
- environment.GetEnvironmentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = environment.Environment.to_json(environment.Environment())
- req.return_value.content = return_value
-
- request = environment.GetEnvironmentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = environment.Environment()
-
- client.get_environment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_environment_rest_bad_request(
- request_type=gcdc_environment.CreateEnvironmentRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_environment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_environment.CreateEnvironmentRequest,
- dict,
- ],
-)
-def test_create_environment_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["environment"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "description": "description_value",
- "version_configs": [{"version": "version_value"}],
- "update_time": {"seconds": 751, "nanos": 543},
- "test_cases_config": {
- "test_cases": ["test_cases_value1", "test_cases_value2"],
- "enable_continuous_run": True,
- "enable_predeployment_run": True,
- },
- "webhook_config": {
- "webhook_overrides": [
- {
- "name": "name_value",
- "display_name": "display_name_value",
- "generic_web_service": {
- "uri": "uri_value",
- "username": "username_value",
- "password": "password_value",
- "request_headers": {},
- "allowed_ca_certs": [
- b"allowed_ca_certs_blob1",
- b"allowed_ca_certs_blob2",
- ],
- "oauth_config": {
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- "scopes": ["scopes_value1", "scopes_value2"],
- },
- "service_agent_auth": 1,
- "webhook_type": 1,
- "http_method": 1,
- "request_body": "request_body_value",
- "parameter_mapping": {},
- },
- "service_directory": {
- "service": "service_value",
- "generic_web_service": {},
- },
- "timeout": {"seconds": 751, "nanos": 543},
- "disabled": True,
- }
- ]
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_environment.CreateEnvironmentRequest.meta.fields["environment"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["environment"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["environment"][field])):
- del request_init["environment"][field][i][subfield]
- else:
- del request_init["environment"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_environment(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_environment_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_create_environment"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_create_environment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_environment.CreateEnvironmentRequest.pb(
- gcdc_environment.CreateEnvironmentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = gcdc_environment.CreateEnvironmentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.create_environment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_environment_rest_bad_request(
- request_type=gcdc_environment.UpdateEnvironmentRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "environment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_environment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_environment.UpdateEnvironmentRequest,
- dict,
- ],
-)
-def test_update_environment_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "environment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- }
- request_init["environment"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4",
- "display_name": "display_name_value",
- "description": "description_value",
- "version_configs": [{"version": "version_value"}],
- "update_time": {"seconds": 751, "nanos": 543},
- "test_cases_config": {
- "test_cases": ["test_cases_value1", "test_cases_value2"],
- "enable_continuous_run": True,
- "enable_predeployment_run": True,
- },
- "webhook_config": {
- "webhook_overrides": [
- {
- "name": "name_value",
- "display_name": "display_name_value",
- "generic_web_service": {
- "uri": "uri_value",
- "username": "username_value",
- "password": "password_value",
- "request_headers": {},
- "allowed_ca_certs": [
- b"allowed_ca_certs_blob1",
- b"allowed_ca_certs_blob2",
- ],
- "oauth_config": {
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- "scopes": ["scopes_value1", "scopes_value2"],
- },
- "service_agent_auth": 1,
- "webhook_type": 1,
- "http_method": 1,
- "request_body": "request_body_value",
- "parameter_mapping": {},
- },
- "service_directory": {
- "service": "service_value",
- "generic_web_service": {},
- },
- "timeout": {"seconds": 751, "nanos": 543},
- "disabled": True,
- }
- ]
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_environment.UpdateEnvironmentRequest.meta.fields["environment"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["environment"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["environment"][field])):
- del request_init["environment"][field][i][subfield]
- else:
- del request_init["environment"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_environment(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_environment_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_update_environment"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_update_environment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_environment.UpdateEnvironmentRequest.pb(
- gcdc_environment.UpdateEnvironmentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = gcdc_environment.UpdateEnvironmentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.update_environment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_environment_rest_bad_request(
- request_type=environment.DeleteEnvironmentRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_environment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.DeleteEnvironmentRequest,
- dict,
- ],
-)
-def test_delete_environment_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_environment(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_environment_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_delete_environment"
- ) as pre:
- pre.assert_not_called()
- pb_message = environment.DeleteEnvironmentRequest.pb(
- environment.DeleteEnvironmentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = environment.DeleteEnvironmentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_environment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_lookup_environment_history_rest_bad_request(
- request_type=environment.LookupEnvironmentHistoryRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.lookup_environment_history(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.LookupEnvironmentHistoryRequest,
- dict,
- ],
-)
-def test_lookup_environment_history_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.LookupEnvironmentHistoryResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = environment.LookupEnvironmentHistoryResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.lookup_environment_history(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.LookupEnvironmentHistoryPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_lookup_environment_history_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_lookup_environment_history"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_lookup_environment_history"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = environment.LookupEnvironmentHistoryRequest.pb(
- environment.LookupEnvironmentHistoryRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = environment.LookupEnvironmentHistoryResponse.to_json(
- environment.LookupEnvironmentHistoryResponse()
- )
- req.return_value.content = return_value
-
- request = environment.LookupEnvironmentHistoryRequest()
+ request = environment.RunContinuousTestRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = environment.LookupEnvironmentHistoryResponse()
+ post.return_value = operations_pb2.Operation()
- client.lookup_environment_history(
+ client.run_continuous_test(
request,
metadata=[
("key", "val"),
@@ -7955,11 +7498,13 @@ def test_lookup_environment_history_rest_interceptors(null_interceptor):
def test_run_continuous_test_rest_bad_request(
- request_type=environment.RunContinuousTestRequest,
+ transport: str = "rest", request_type=environment.RunContinuousTestRequest
):
client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
"environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
@@ -7971,173 +7516,200 @@ def test_run_continuous_test_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
client.run_continuous_test(request)
+def test_run_continuous_test_rest_error():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
@pytest.mark.parametrize(
"request_type",
[
- environment.RunContinuousTestRequest,
+ environment.ListContinuousTestResultsRequest,
dict,
],
)
-def test_run_continuous_test_rest_call_success(request_type):
+def test_list_continuous_test_results_rest(request_type):
client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
request_init = {
- "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
}
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = environment.ListContinuousTestResultsResponse(
+ next_page_token="next_page_token_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.ListContinuousTestResultsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.run_continuous_test(request)
+ response = client.list_continuous_test_results(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
+ assert isinstance(response, pagers.ListContinuousTestResultsPager)
+ assert response.next_page_token == "next_page_token_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_run_continuous_test_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_run_continuous_test"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_run_continuous_test"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = environment.RunContinuousTestRequest.pb(
- environment.RunContinuousTestRequest()
+def test_list_continuous_test_results_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = environment.RunContinuousTestRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ # Ensure method has been cached
+ assert (
+ client._transport.list_continuous_test_results
+ in client._transport._wrapped_methods
+ )
- client.run_continuous_test(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[
+ client._transport.list_continuous_test_results
+ ] = mock_rpc
- pre.assert_called_once()
- post.assert_called_once()
+ request = {}
+ client.list_continuous_test_results(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_continuous_test_results_rest_bad_request(
+ client.list_continuous_test_results(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_list_continuous_test_results_rest_required_fields(
request_type=environment.ListContinuousTestResultsRequest,
):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
+ transport_class = transports.EnvironmentsRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_continuous_test_results(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_continuous_test_results._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.ListContinuousTestResultsRequest,
- dict,
- ],
-)
-def test_list_continuous_test_results_rest_call_success(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_continuous_test_results._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "page_size",
+ "page_token",
+ )
)
+ jsonified_request.update(unset_fields)
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
request = request_type(**request_init)
+ # Designate an appropriate value for the returned response.
+ return_value = environment.ListContinuousTestResultsResponse()
# Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = environment.ListContinuousTestResultsResponse(
- next_page_token="next_page_token_value",
- )
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = environment.ListContinuousTestResultsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ response = client.list_continuous_test_results(request)
- # Convert return value to protobuf type
- return_value = environment.ListContinuousTestResultsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_continuous_test_results(request)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListContinuousTestResultsPager)
- assert response.next_page_token == "next_page_token_value"
+
+def test_list_continuous_test_results_rest_unset_required_fields():
+ transport = transports.EnvironmentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.list_continuous_test_results._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "pageSize",
+ "pageToken",
+ )
+ )
+ & set(("parent",))
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -8149,7 +7721,6 @@ def test_list_continuous_test_results_rest_interceptors(null_interceptor):
else transports.EnvironmentsRestInterceptor(),
)
client = EnvironmentsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -8171,12 +7742,14 @@ def test_list_continuous_test_results_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = environment.ListContinuousTestResultsResponse.to_json(
- environment.ListContinuousTestResultsResponse()
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ environment.ListContinuousTestResultsResponse.to_json(
+ environment.ListContinuousTestResultsResponse()
+ )
)
- req.return_value.content = return_value
request = environment.ListContinuousTestResultsRequest()
metadata = [
@@ -8198,13 +7771,17 @@ def test_list_continuous_test_results_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_deploy_flow_rest_bad_request(request_type=environment.DeployFlowRequest):
+def test_list_continuous_test_results_rest_bad_request(
+ transport: str = "rest", request_type=environment.ListContinuousTestResultsRequest
+):
client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
}
request = request_type(**request_init)
@@ -8213,351 +7790,375 @@ def test_deploy_flow_rest_bad_request(request_type=environment.DeployFlowRequest
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.deploy_flow(request)
+ client.list_continuous_test_results(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- environment.DeployFlowRequest,
- dict,
- ],
-)
-def test_deploy_flow_rest_call_success(request_type):
+def test_list_continuous_test_results_rest_flattened():
client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = environment.ListContinuousTestResultsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = environment.ListContinuousTestResultsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.deploy_flow(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_deploy_flow_rest_interceptors(null_interceptor):
- transport = transports.EnvironmentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.EnvironmentsRestInterceptor(),
- )
- client = EnvironmentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.EnvironmentsRestInterceptor, "post_deploy_flow"
- ) as post, mock.patch.object(
- transports.EnvironmentsRestInterceptor, "pre_deploy_flow"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = environment.DeployFlowRequest.pb(environment.DeployFlowRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
- request = environment.DeployFlowRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ client.list_continuous_test_results(**mock_args)
- client.deploy_flow(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/continuousTestResults"
+ % client.transport._host,
+ args[1],
)
- pre.assert_called_once()
- post.assert_called_once()
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_list_continuous_test_results_rest_flattened_error(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ transport=transport,
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_continuous_test_results(
+ environment.ListContinuousTestResultsRequest(),
+ parent="parent_value",
+ )
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
+def test_list_continuous_test_results_rest_pager(transport: str = "rest"):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
+ # TODO(kbandes): remove this mock unless there's a good reason for it.
+ # with mock.patch.object(path_template, 'transcode') as transcode:
+ # Set the response as a series of pages
+ response = (
+ environment.ListContinuousTestResultsResponse(
+ continuous_test_results=[
+ environment.ContinuousTestResult(),
+ environment.ContinuousTestResult(),
+ environment.ContinuousTestResult(),
+ ],
+ next_page_token="abc",
+ ),
+ environment.ListContinuousTestResultsResponse(
+ continuous_test_results=[],
+ next_page_token="def",
+ ),
+ environment.ListContinuousTestResultsResponse(
+ continuous_test_results=[
+ environment.ContinuousTestResult(),
+ ],
+ next_page_token="ghi",
+ ),
+ environment.ListContinuousTestResultsResponse(
+ continuous_test_results=[
+ environment.ContinuousTestResult(),
+ environment.ContinuousTestResult(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ # Wrap the values into proper Response objs
+ response = tuple(
+ environment.ListContinuousTestResultsResponse.to_json(x) for x in response
+ )
+ return_values = tuple(Response() for i in response)
+ for return_val, response_val in zip(return_values, response):
+ return_val._content = response_val.encode("UTF-8")
+ return_val.status_code = 200
+ req.side_effect = return_values
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+ pager = client.list_continuous_test_results(request=sample_request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, environment.ContinuousTestResult) for i in results)
+
+ pages = list(client.list_continuous_test_results(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.ListLocationsRequest,
+ environment.DeployFlowRequest,
dict,
],
)
-def test_list_locations_rest(request_type):
+def test_deploy_flow_rest(request_type):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.list_locations(request)
+ response = client.deploy_flow(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ assert response.operation.name == "operations/spam"
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_deploy_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.deploy_flow in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.deploy_flow] = mock_rpc
+
+ request = {}
+ client.deploy_flow(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.deploy_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_deploy_flow_rest_required_fields(request_type=environment.DeployFlowRequest):
+ transport_class = transports.EnvironmentsRestTransport
+
+ request_init = {}
+ request_init["environment"] = ""
+ request_init["flow_version"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).deploy_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["environment"] = "environment_value"
+ jsonified_request["flowVersion"] = "flow_version_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).deploy_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "environment" in jsonified_request
+ assert jsonified_request["environment"] == "environment_value"
+ assert "flowVersion" in jsonified_request
+ assert jsonified_request["flowVersion"] == "flow_version_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1/operations/sample2"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- req.return_value = response_value
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- response = client.cancel_operation(request)
+ response = client.deploy_flow(request)
- # Establish that the response is the type that we expect.
- assert response is None
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_deploy_flow_rest_unset_required_fields():
+ transport = transports.EnvironmentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
+ unset_fields = transport.deploy_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(())
+ & set(
+ (
+ "environment",
+ "flowVersion",
+ )
+ )
+ )
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = EnvironmentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_deploy_flow_rest_interceptors(null_interceptor):
+ transport = transports.EnvironmentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.EnvironmentsRestInterceptor(),
)
+ client = EnvironmentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "post_deploy_flow"
+ ) as post, mock.patch.object(
+ transports.EnvironmentsRestInterceptor, "pre_deploy_flow"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = environment.DeployFlowRequest.pb(environment.DeployFlowRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- req.return_value = response_value
+ request = environment.DeployFlowRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- response = client.get_operation(request)
+ client.deploy_flow(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_deploy_flow_rest_bad_request(
+ transport: str = "rest", request_type=environment.DeployFlowRequest
):
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "environment": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -8565,264 +8166,122 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ client.deploy_flow(request)
-def test_initialize_client_w_rest():
+def test_deploy_flow_rest_error():
client = EnvironmentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_environments_empty_call_rest():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_environments), "__call__"
- ) as call:
- client.list_environments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListEnvironmentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_environment_empty_call_rest():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_environment), "__call__") as call:
- client.get_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.GetEnvironmentRequest()
-
- assert args[0] == request_msg
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_environment_empty_call_rest():
- client = EnvironmentsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_environment), "__call__"
- ) as call:
- client.create_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.CreateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_environment_empty_call_rest():
- client = EnvironmentsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = EnvironmentsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_environment), "__call__"
- ) as call:
- client.update_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_environment.UpdateEnvironmentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_environment_empty_call_rest():
- client = EnvironmentsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = EnvironmentsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_environment), "__call__"
- ) as call:
- client.delete_environment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeleteEnvironmentRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = EnvironmentsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_lookup_environment_history_empty_call_rest():
- client = EnvironmentsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.lookup_environment_history), "__call__"
- ) as call:
- client.lookup_environment_history(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.LookupEnvironmentHistoryRequest()
-
- assert args[0] == request_msg
+ with pytest.raises(ValueError):
+ client = EnvironmentsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_run_continuous_test_empty_call_rest():
- client = EnvironmentsClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.run_continuous_test), "__call__"
- ) as call:
- client.run_continuous_test(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.RunContinuousTestRequest()
-
- assert args[0] == request_msg
+ client = EnvironmentsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_continuous_test_results_empty_call_rest():
- client = EnvironmentsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EnvironmentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_continuous_test_results), "__call__"
- ) as call:
- client.list_continuous_test_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.ListContinuousTestResultsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_deploy_flow_empty_call_rest():
- client = EnvironmentsClient(
+ transport = transports.EnvironmentsGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.deploy_flow), "__call__") as call:
- client.deploy_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = environment.DeployFlowRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EnvironmentsGrpcTransport,
+ transports.EnvironmentsGrpcAsyncIOTransport,
+ transports.EnvironmentsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_environments_rest_lro_client():
- client = EnvironmentsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = EnvironmentsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -9070,15 +8529,32 @@ def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class
)
-def test_environments_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.EnvironmentsRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_environments_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.EnvironmentsRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_environments_rest_lro_client():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -9556,115 +9032,415 @@ def test_parse_common_billing_account_path():
}
path = EnvironmentsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = EnvironmentsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = EnvironmentsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "oyster"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = EnvironmentsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nudibranch",
+ }
+ path = EnvironmentsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EnvironmentsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "cuttlefish"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = EnvironmentsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "mussel",
+ }
+ path = EnvironmentsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EnvironmentsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "winkle"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = EnvironmentsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nautilus",
+ }
+ path = EnvironmentsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EnvironmentsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "scallop"
+ location = "abalone"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = EnvironmentsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ }
+ path = EnvironmentsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EnvironmentsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.EnvironmentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.EnvironmentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = EnvironmentsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = EnvironmentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "oyster"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = EnvironmentsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "nudibranch",
- }
- path = EnvironmentsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = EnvironmentsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "cuttlefish"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = EnvironmentsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "mussel",
- }
- path = EnvironmentsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = EnvironmentsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "winkle"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = EnvironmentsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "nautilus",
- }
- path = EnvironmentsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = EnvironmentsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "scallop"
- location = "abalone"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = EnvironmentsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "squid",
- "location": "clam",
- }
- path = EnvironmentsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = EnvironmentsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.EnvironmentsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.EnvironmentsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = EnvironmentsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -9694,7 +9470,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9747,7 +9523,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9792,7 +9568,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -9833,7 +9609,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9888,7 +9664,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9935,7 +9711,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -9978,7 +9754,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10033,7 +9809,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10080,7 +9856,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -10123,7 +9899,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10178,7 +9954,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10225,7 +10001,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10268,7 +10044,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10320,7 +10096,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = EnvironmentsAsyncClient(credentials=async_anonymous_credentials())
+ client = EnvironmentsAsyncClient(credentials=ga_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.
@@ -10366,7 +10142,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10382,41 +10158,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = EnvironmentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = EnvironmentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = EnvironmentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_examples.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_examples.py
index c0fefc3b0dde..989a9275e21c 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_examples.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_examples.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,8 +36,16 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.examples import (
ExamplesAsyncClient,
@@ -67,24 +57,10 @@
from google.cloud.dialogflowcx_v3beta1.types import example as gcdc_example
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1139,6 +1115,25 @@ def test_create_example(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_create_example_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 = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_example), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_example.CreateExampleRequest()
+
+
def test_create_example_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1202,6 +1197,34 @@ def test_create_example_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_example_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_example), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+ )
+ response = await client.create_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_example.CreateExampleRequest()
+
+
@pytest.mark.asyncio
async def test_create_example_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1210,7 +1233,7 @@ async def test_create_example_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1225,23 +1248,27 @@ async def test_create_example_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_example
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_example(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_example(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1249,7 +1276,7 @@ async def test_create_example_async(
transport: str = "grpc_asyncio", request_type=gcdc_example.CreateExampleRequest
):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1325,7 +1352,7 @@ def test_create_example_field_headers():
@pytest.mark.asyncio
async def test_create_example_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1400,7 +1427,7 @@ def test_create_example_flattened_error():
@pytest.mark.asyncio
async def test_create_example_flattened_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1433,7 +1460,7 @@ async def test_create_example_flattened_async():
@pytest.mark.asyncio
async def test_create_example_flattened_error_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1479,6 +1506,25 @@ def test_delete_example(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_example_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 = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_example), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.DeleteExampleRequest()
+
+
def test_delete_example_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1542,6 +1588,25 @@ def test_delete_example_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_example_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_example), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.DeleteExampleRequest()
+
+
@pytest.mark.asyncio
async def test_delete_example_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1550,7 +1615,7 @@ async def test_delete_example_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1565,23 +1630,27 @@ async def test_delete_example_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_example
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_example(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_example(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1589,7 +1658,7 @@ async def test_delete_example_async(
transport: str = "grpc_asyncio", request_type=example.DeleteExampleRequest
):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1650,7 +1719,7 @@ def test_delete_example_field_headers():
@pytest.mark.asyncio
async def test_delete_example_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1718,7 +1787,7 @@ def test_delete_example_flattened_error():
@pytest.mark.asyncio
async def test_delete_example_flattened_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1745,7 +1814,7 @@ async def test_delete_example_flattened_async():
@pytest.mark.asyncio
async def test_delete_example_flattened_error_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1793,6 +1862,25 @@ def test_list_examples(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_examples_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 = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_examples), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_examples()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.ListExamplesRequest()
+
+
def test_list_examples_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1860,6 +1948,29 @@ def test_list_examples_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_examples_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_examples), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ example.ListExamplesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_examples()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.ListExamplesRequest()
+
+
@pytest.mark.asyncio
async def test_list_examples_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1868,7 +1979,7 @@ async def test_list_examples_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1883,23 +1994,27 @@ async def test_list_examples_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_examples
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_examples(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_examples(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1907,7 +2022,7 @@ async def test_list_examples_async(
transport: str = "grpc_asyncio", request_type=example.ListExamplesRequest
):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1973,7 +2088,7 @@ def test_list_examples_field_headers():
@pytest.mark.asyncio
async def test_list_examples_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2043,7 +2158,7 @@ def test_list_examples_flattened_error():
@pytest.mark.asyncio
async def test_list_examples_flattened_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2072,7 +2187,7 @@ async def test_list_examples_flattened_async():
@pytest.mark.asyncio
async def test_list_examples_flattened_error_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2122,16 +2237,12 @@ def test_list_examples_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_examples(request={}, retry=retry, timeout=timeout)
+ pager = client.list_examples(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -2182,7 +2293,7 @@ def test_list_examples_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_examples_async_pager():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2232,7 +2343,7 @@ async def test_list_examples_async_pager():
@pytest.mark.asyncio
async def test_list_examples_async_pages():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2324,6 +2435,25 @@ def test_get_example(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_get_example_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 = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_example), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.GetExampleRequest()
+
+
def test_get_example_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2387,6 +2517,34 @@ def test_get_example_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_example_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_example), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+ )
+ response = await client.get_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == example.GetExampleRequest()
+
+
@pytest.mark.asyncio
async def test_get_example_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2395,7 +2553,7 @@ async def test_get_example_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2410,23 +2568,27 @@ async def test_get_example_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_example
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_example(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_example(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2434,7 +2596,7 @@ async def test_get_example_async(
transport: str = "grpc_asyncio", request_type=example.GetExampleRequest
):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2510,7 +2672,7 @@ def test_get_example_field_headers():
@pytest.mark.asyncio
async def test_get_example_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2578,7 +2740,7 @@ def test_get_example_flattened_error():
@pytest.mark.asyncio
async def test_get_example_flattened_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2605,7 +2767,7 @@ async def test_get_example_flattened_async():
@pytest.mark.asyncio
async def test_get_example_flattened_error_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2663,6 +2825,25 @@ def test_update_example(request_type, transport: str = "grpc"):
assert response.language_code == "language_code_value"
+def test_update_example_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 = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_example), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_example.UpdateExampleRequest()
+
+
def test_update_example_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2722,6 +2903,34 @@ def test_update_example_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_example_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_example), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+ )
+ response = await client.update_example()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_example.UpdateExampleRequest()
+
+
@pytest.mark.asyncio
async def test_update_example_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2730,7 +2939,7 @@ async def test_update_example_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2745,23 +2954,27 @@ async def test_update_example_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_example
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_example(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_example(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2769,7 +2982,7 @@ async def test_update_example_async(
transport: str = "grpc_asyncio", request_type=gcdc_example.UpdateExampleRequest
):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2845,7 +3058,7 @@ def test_update_example_field_headers():
@pytest.mark.asyncio
async def test_update_example_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2920,7 +3133,7 @@ def test_update_example_flattened_error():
@pytest.mark.asyncio
async def test_update_example_flattened_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2953,7 +3166,7 @@ async def test_update_example_flattened_async():
@pytest.mark.asyncio
async def test_update_example_flattened_error_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2966,22 +3179,183 @@ async def test_update_example_flattened_error_async():
)
-def test_create_example_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.create_example in client._transport._wrapped_methods
-
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_example.CreateExampleRequest,
+ dict,
+ ],
+)
+def test_create_example_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request_init["example"] = {
+ "name": "name_value",
+ "playbook_input": {
+ "preceding_conversation_summary": "preceding_conversation_summary_value",
+ "action_parameters": {"fields": {}},
+ },
+ "playbook_output": {
+ "execution_summary": "execution_summary_value",
+ "action_parameters": {},
+ },
+ "actions": [
+ {
+ "user_utterance": {"text": "text_value"},
+ "agent_utterance": {"text": "text_value"},
+ "tool_use": {
+ "tool": "tool_value",
+ "action": "action_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ },
+ "playbook_invocation": {
+ "playbook": "playbook_value",
+ "playbook_input": {},
+ "playbook_output": {},
+ "playbook_state": 1,
+ },
+ "flow_invocation": {
+ "flow": "flow_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ "flow_state": 1,
+ },
+ }
+ ],
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "token_count": 1193,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "conversation_state": 1,
+ "language_code": "language_code_value",
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_example.CreateExampleRequest.meta.fields["example"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["example"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["example"][field])):
+ del request_init["example"][field][i][subfield]
+ else:
+ del request_init["example"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_example.Example.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_example(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_example.Example)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.token_count == 1193
+ assert response.conversation_state == gcdc_example.OutputState.OUTPUT_STATE_OK
+ assert response.language_code == "language_code_value"
+
+
+def test_create_example_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_example in client._transport._wrapped_methods
+
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
@@ -3094,6 +3468,85 @@ def test_create_example_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_example_rest_interceptors(null_interceptor):
+ transport = transports.ExamplesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
+ )
+ client = ExamplesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExamplesRestInterceptor, "post_create_example"
+ ) as post, mock.patch.object(
+ transports.ExamplesRestInterceptor, "pre_create_example"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_example.CreateExampleRequest.pb(
+ gcdc_example.CreateExampleRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_example.Example.to_json(gcdc_example.Example())
+
+ request = gcdc_example.CreateExampleRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_example.Example()
+
+ client.create_example(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_example_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_example.CreateExampleRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_example(request)
+
+
def test_create_example_rest_flattened():
client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3155,11 +3608,54 @@ def test_create_example_rest_flattened_error(transport: str = "rest"):
)
-def test_delete_example_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExamplesClient(
+def test_create_example_rest_error():
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ example.DeleteExampleRequest,
+ dict,
+ ],
+)
+def test_delete_example_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_example(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_example_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
@@ -3269,6 +3765,77 @@ def test_delete_example_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_example_rest_interceptors(null_interceptor):
+ transport = transports.ExamplesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
+ )
+ client = ExamplesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExamplesRestInterceptor, "pre_delete_example"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = example.DeleteExampleRequest.pb(example.DeleteExampleRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = example.DeleteExampleRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_example(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_example_rest_bad_request(
+ transport: str = "rest", request_type=example.DeleteExampleRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_example(request)
+
+
def test_delete_example_rest_flattened():
client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3326,6 +3893,54 @@ def test_delete_example_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_example_rest_error():
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ example.ListExamplesRequest,
+ dict,
+ ],
+)
+def test_list_examples_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = example.ListExamplesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = example.ListExamplesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_examples(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListExamplesPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_examples_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3460,6 +4075,85 @@ def test_list_examples_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_examples_rest_interceptors(null_interceptor):
+ transport = transports.ExamplesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
+ )
+ client = ExamplesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExamplesRestInterceptor, "post_list_examples"
+ ) as post, mock.patch.object(
+ transports.ExamplesRestInterceptor, "pre_list_examples"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = example.ListExamplesRequest.pb(example.ListExamplesRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = example.ListExamplesResponse.to_json(
+ example.ListExamplesResponse()
+ )
+
+ request = example.ListExamplesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = example.ListExamplesResponse()
+
+ client.list_examples(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_examples_rest_bad_request(
+ transport: str = "rest", request_type=example.ListExamplesRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_examples(request)
+
+
def test_list_examples_rest_flattened():
client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3582,18 +4276,70 @@ def test_list_examples_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
-def test_get_example_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ example.GetExampleRequest,
+ dict,
+ ],
+)
+def test_get_example_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = example.Example.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_example(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, example.Example)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.token_count == 1193
+ assert response.conversation_state == example.OutputState.OUTPUT_STATE_OK
+ assert response.language_code == "language_code_value"
+
+
+def test_get_example_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
# Ensure method has been cached
assert client._transport.get_example in client._transport._wrapped_methods
@@ -3699,6 +4445,83 @@ def test_get_example_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_example_rest_interceptors(null_interceptor):
+ transport = transports.ExamplesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
+ )
+ client = ExamplesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExamplesRestInterceptor, "post_get_example"
+ ) as post, mock.patch.object(
+ transports.ExamplesRestInterceptor, "pre_get_example"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = example.GetExampleRequest.pb(example.GetExampleRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = example.Example.to_json(example.Example())
+
+ request = example.GetExampleRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = example.Example()
+
+ client.get_example(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_example_rest_bad_request(
+ transport: str = "rest", request_type=example.GetExampleRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_example(request)
+
+
def test_get_example_rest_flattened():
client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3758,62 +4581,231 @@ def test_get_example_rest_flattened_error(transport: str = "rest"):
)
-def test_update_example_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_example in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.update_example] = mock_rpc
+def test_get_example_rest_error():
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- request = {}
- client.update_example(request)
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_example.UpdateExampleRequest,
+ dict,
+ ],
+)
+def test_update_example_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- client.update_example(request)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "example": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ }
+ request_init["example"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5",
+ "playbook_input": {
+ "preceding_conversation_summary": "preceding_conversation_summary_value",
+ "action_parameters": {"fields": {}},
+ },
+ "playbook_output": {
+ "execution_summary": "execution_summary_value",
+ "action_parameters": {},
+ },
+ "actions": [
+ {
+ "user_utterance": {"text": "text_value"},
+ "agent_utterance": {"text": "text_value"},
+ "tool_use": {
+ "tool": "tool_value",
+ "action": "action_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ },
+ "playbook_invocation": {
+ "playbook": "playbook_value",
+ "playbook_input": {},
+ "playbook_output": {},
+ "playbook_state": 1,
+ },
+ "flow_invocation": {
+ "flow": "flow_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ "flow_state": 1,
+ },
+ }
+ ],
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "token_count": 1193,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "conversation_state": 1,
+ "language_code": "language_code_value",
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_example.UpdateExampleRequest.meta.fields["example"]
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
-def test_update_example_rest_required_fields(
- request_type=gcdc_example.UpdateExampleRequest,
-):
- transport_class = transports.ExamplesRestTransport
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
- # verify fields with default values are dropped
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_example._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
+ subfields_not_in_runtime = []
- # verify required fields with default values are now present
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["example"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["example"][field])):
+ del request_init["example"][field][i][subfield]
+ else:
+ del request_init["example"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_example.Example(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ token_count=1193,
+ conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
+ language_code="language_code_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_example.Example.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_example(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_example.Example)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.token_count == 1193
+ assert response.conversation_state == gcdc_example.OutputState.OUTPUT_STATE_OK
+ assert response.language_code == "language_code_value"
+
+
+def test_update_example_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_example in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_example] = mock_rpc
+
+ request = {}
+ client.update_example(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_example(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_example_rest_required_fields(
+ request_type=gcdc_example.UpdateExampleRequest,
+):
+ transport_class = transports.ExamplesRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_example._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
@@ -3875,6 +4867,87 @@ def test_update_example_rest_unset_required_fields():
assert set(unset_fields) == (set(("updateMask",)) & set(("example",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_example_rest_interceptors(null_interceptor):
+ transport = transports.ExamplesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
+ )
+ client = ExamplesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExamplesRestInterceptor, "post_update_example"
+ ) as post, mock.patch.object(
+ transports.ExamplesRestInterceptor, "pre_update_example"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_example.UpdateExampleRequest.pb(
+ gcdc_example.UpdateExampleRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_example.Example.to_json(gcdc_example.Example())
+
+ request = gcdc_example.UpdateExampleRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_example.Example()
+
+ client.update_example(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_example_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_example.UpdateExampleRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "example": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_example(request)
+
+
def test_update_example_rest_flattened():
client = ExamplesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3938,6 +5011,12 @@ def test_update_example_rest_flattened_error(transport: str = "rest"):
)
+def test_update_example_rest_error():
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.ExamplesGrpcTransport(
@@ -4027,1528 +5106,21 @@ def test_transport_adc(transport_class):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = ExamplesClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_example_empty_call_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_example), "__call__") as call:
- call.return_value = gcdc_example.Example()
- client.create_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.CreateExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_example_empty_call_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_example), "__call__") as call:
- call.return_value = None
- client.delete_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.DeleteExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_examples_empty_call_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_examples), "__call__") as call:
- call.return_value = example.ListExamplesResponse()
- client.list_examples(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.ListExamplesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_example_empty_call_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_example), "__call__") as call:
- call.return_value = example.Example()
- client.get_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.GetExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_example_empty_call_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_example), "__call__") as call:
- call.return_value = gcdc_example.Example()
- client.update_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.UpdateExampleRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ExamplesAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_example_empty_call_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_example), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
- )
- await client.create_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.CreateExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_example_empty_call_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_example), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.DeleteExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_examples_empty_call_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_examples), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- example.ListExamplesResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_examples(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.ListExamplesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_example_empty_call_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_example), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
- )
- await client.get_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.GetExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_example_empty_call_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_example), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
- )
- await client.update_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.UpdateExampleRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = ExamplesClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_create_example_rest_bad_request(
- request_type=gcdc_example.CreateExampleRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_example(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_example.CreateExampleRequest,
- dict,
- ],
-)
-def test_create_example_rest_call_success(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request_init["example"] = {
- "name": "name_value",
- "playbook_input": {
- "preceding_conversation_summary": "preceding_conversation_summary_value",
- "action_parameters": {"fields": {}},
- },
- "playbook_output": {
- "execution_summary": "execution_summary_value",
- "action_parameters": {},
- },
- "actions": [
- {
- "user_utterance": {"text": "text_value"},
- "agent_utterance": {"text": "text_value"},
- "tool_use": {
- "tool": "tool_value",
- "action": "action_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- },
- "playbook_invocation": {
- "playbook": "playbook_value",
- "playbook_input": {},
- "playbook_output": {},
- "playbook_state": 1,
- },
- "flow_invocation": {
- "flow": "flow_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- "flow_state": 1,
- },
- }
- ],
- "display_name": "display_name_value",
- "description": "description_value",
- "token_count": 1193,
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "conversation_state": 1,
- "language_code": "language_code_value",
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_example.CreateExampleRequest.meta.fields["example"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["example"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["example"][field])):
- del request_init["example"][field][i][subfield]
- else:
- del request_init["example"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_example.Example.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_example(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_example.Example)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.token_count == 1193
- assert response.conversation_state == gcdc_example.OutputState.OUTPUT_STATE_OK
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_example_rest_interceptors(null_interceptor):
- transport = transports.ExamplesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
- )
- client = ExamplesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExamplesRestInterceptor, "post_create_example"
- ) as post, mock.patch.object(
- transports.ExamplesRestInterceptor, "pre_create_example"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_example.CreateExampleRequest.pb(
- gcdc_example.CreateExampleRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_example.Example.to_json(gcdc_example.Example())
- req.return_value.content = return_value
-
- request = gcdc_example.CreateExampleRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_example.Example()
-
- client.create_example(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_example_rest_bad_request(request_type=example.DeleteExampleRequest):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_example(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- example.DeleteExampleRequest,
- dict,
- ],
-)
-def test_delete_example_rest_call_success(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_example(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_example_rest_interceptors(null_interceptor):
- transport = transports.ExamplesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
- )
- client = ExamplesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExamplesRestInterceptor, "pre_delete_example"
- ) as pre:
- pre.assert_not_called()
- pb_message = example.DeleteExampleRequest.pb(example.DeleteExampleRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = example.DeleteExampleRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_example(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_list_examples_rest_bad_request(request_type=example.ListExamplesRequest):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_examples(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- example.ListExamplesRequest,
- dict,
- ],
-)
-def test_list_examples_rest_call_success(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = example.ListExamplesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = example.ListExamplesResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_examples(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListExamplesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_examples_rest_interceptors(null_interceptor):
- transport = transports.ExamplesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
- )
- client = ExamplesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExamplesRestInterceptor, "post_list_examples"
- ) as post, mock.patch.object(
- transports.ExamplesRestInterceptor, "pre_list_examples"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = example.ListExamplesRequest.pb(example.ListExamplesRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = example.ListExamplesResponse.to_json(
- example.ListExamplesResponse()
- )
- req.return_value.content = return_value
-
- request = example.ListExamplesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = example.ListExamplesResponse()
-
- client.list_examples(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_example_rest_bad_request(request_type=example.GetExampleRequest):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_example(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- example.GetExampleRequest,
- dict,
- ],
-)
-def test_get_example_rest_call_success(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = example.Example.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_example(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, example.Example)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.token_count == 1193
- assert response.conversation_state == example.OutputState.OUTPUT_STATE_OK
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_example_rest_interceptors(null_interceptor):
- transport = transports.ExamplesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
- )
- client = ExamplesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExamplesRestInterceptor, "post_get_example"
- ) as post, mock.patch.object(
- transports.ExamplesRestInterceptor, "pre_get_example"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = example.GetExampleRequest.pb(example.GetExampleRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = example.Example.to_json(example.Example())
- req.return_value.content = return_value
-
- request = example.GetExampleRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = example.Example()
-
- client.get_example(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_example_rest_bad_request(
- request_type=gcdc_example.UpdateExampleRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "example": {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_example(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_example.UpdateExampleRequest,
- dict,
- ],
-)
-def test_update_example_rest_call_success(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "example": {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5"
- }
- }
- request_init["example"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5",
- "playbook_input": {
- "preceding_conversation_summary": "preceding_conversation_summary_value",
- "action_parameters": {"fields": {}},
- },
- "playbook_output": {
- "execution_summary": "execution_summary_value",
- "action_parameters": {},
- },
- "actions": [
- {
- "user_utterance": {"text": "text_value"},
- "agent_utterance": {"text": "text_value"},
- "tool_use": {
- "tool": "tool_value",
- "action": "action_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- },
- "playbook_invocation": {
- "playbook": "playbook_value",
- "playbook_input": {},
- "playbook_output": {},
- "playbook_state": 1,
- },
- "flow_invocation": {
- "flow": "flow_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- "flow_state": 1,
- },
- }
- ],
- "display_name": "display_name_value",
- "description": "description_value",
- "token_count": 1193,
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "conversation_state": 1,
- "language_code": "language_code_value",
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_example.UpdateExampleRequest.meta.fields["example"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["example"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["example"][field])):
- del request_init["example"][field][i][subfield]
- else:
- del request_init["example"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_example.Example(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- token_count=1193,
- conversation_state=gcdc_example.OutputState.OUTPUT_STATE_OK,
- language_code="language_code_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_example.Example.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_example(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_example.Example)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.token_count == 1193
- assert response.conversation_state == gcdc_example.OutputState.OUTPUT_STATE_OK
- assert response.language_code == "language_code_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_example_rest_interceptors(null_interceptor):
- transport = transports.ExamplesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(),
- )
- client = ExamplesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExamplesRestInterceptor, "post_update_example"
- ) as post, mock.patch.object(
- transports.ExamplesRestInterceptor, "pre_update_example"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_example.UpdateExampleRequest.pb(
- gcdc_example.UpdateExampleRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_example.Example.to_json(gcdc_example.Example())
- req.return_value.content = return_value
-
- request = gcdc_example.UpdateExampleRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_example.Example()
-
- client.update_example(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_example_empty_call_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_example), "__call__") as call:
- client.create_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.CreateExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_example_empty_call_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_example), "__call__") as call:
- client.delete_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.DeleteExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_examples_empty_call_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_examples), "__call__") as call:
- client.list_examples(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.ListExamplesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_example_empty_call_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_example), "__call__") as call:
- client.get_example(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = example.GetExampleRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_example_empty_call_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_example), "__call__") as call:
- client.update_example(request=None)
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_example.UpdateExampleRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = ExamplesClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6134,115 +5706,415 @@ def test_parse_common_billing_account_path():
}
path = ExamplesClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = ExamplesClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = ExamplesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "squid"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = ExamplesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "clam",
+ }
+ path = ExamplesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExamplesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "whelk"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = ExamplesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "octopus",
+ }
+ path = ExamplesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExamplesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "oyster"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = ExamplesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nudibranch",
+ }
+ path = ExamplesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExamplesClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "cuttlefish"
+ location = "mussel"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = ExamplesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "winkle",
+ "location": "nautilus",
+ }
+ path = ExamplesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExamplesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ExamplesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ExamplesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ExamplesClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = ExamplesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "squid"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ExamplesClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "clam",
- }
- path = ExamplesClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ExamplesClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "whelk"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = ExamplesClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "octopus",
- }
- path = ExamplesClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = ExamplesClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "oyster"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ExamplesClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "nudibranch",
- }
- path = ExamplesClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ExamplesClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "cuttlefish"
- location = "mussel"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ExamplesClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "winkle",
- "location": "nautilus",
- }
- path = ExamplesClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = ExamplesClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.ExamplesTransport, "_prep_wrapped_messages"
- ) as prep:
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.ExamplesTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = ExamplesClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6272,7 +6144,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6325,7 +6197,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6370,7 +6242,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6411,7 +6283,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6466,7 +6338,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6513,7 +6385,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6556,7 +6428,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6611,7 +6483,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6658,7 +6530,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -6701,7 +6573,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6756,7 +6628,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6803,7 +6675,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6846,7 +6718,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6898,7 +6770,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = ExamplesAsyncClient(credentials=async_anonymous_credentials())
+ client = ExamplesAsyncClient(credentials=ga_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.
@@ -6944,7 +6816,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6960,41 +6832,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = ExamplesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = ExamplesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = ExamplesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py
index 2c858d196960..edb954a2b88b 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -55,7 +37,15 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.experiments import (
ExperimentsAsyncClient,
@@ -67,24 +57,10 @@
from google.cloud.dialogflowcx_v3beta1.types import experiment
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1148,6 +1124,25 @@ def test_list_experiments(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_experiments_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_experiments), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_experiments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.ListExperimentsRequest()
+
+
def test_list_experiments_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1215,6 +1210,29 @@ def test_list_experiments_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_experiments_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_experiments), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ experiment.ListExperimentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_experiments()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.ListExperimentsRequest()
+
+
@pytest.mark.asyncio
async def test_list_experiments_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1223,7 +1241,7 @@ async def test_list_experiments_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1238,23 +1256,27 @@ async def test_list_experiments_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_experiments
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_experiments(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_experiments(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1262,7 +1284,7 @@ async def test_list_experiments_async(
transport: str = "grpc_asyncio", request_type=experiment.ListExperimentsRequest
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1328,7 +1350,7 @@ def test_list_experiments_field_headers():
@pytest.mark.asyncio
async def test_list_experiments_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1398,7 +1420,7 @@ def test_list_experiments_flattened_error():
@pytest.mark.asyncio
async def test_list_experiments_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1427,7 +1449,7 @@ async def test_list_experiments_flattened_async():
@pytest.mark.asyncio
async def test_list_experiments_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1477,16 +1499,12 @@ def test_list_experiments_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_experiments(request={}, retry=retry, timeout=timeout)
+ pager = client.list_experiments(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1537,7 +1555,7 @@ def test_list_experiments_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_experiments_async_pager():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1587,7 +1605,7 @@ async def test_list_experiments_async_pager():
@pytest.mark.asyncio
async def test_list_experiments_async_pages():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1677,6 +1695,25 @@ def test_get_experiment(request_type, transport: str = "grpc"):
assert response.rollout_failure_reason == "rollout_failure_reason_value"
+def test_get_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_experiment), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.GetExperimentRequest()
+
+
def test_get_experiment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1740,6 +1777,33 @@ def test_get_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_experiment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+ )
+ response = await client.get_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.GetExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_get_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1748,7 +1812,7 @@ async def test_get_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1763,23 +1827,27 @@ async def test_get_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1787,7 +1855,7 @@ async def test_get_experiment_async(
transport: str = "grpc_asyncio", request_type=experiment.GetExperimentRequest
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1861,7 +1929,7 @@ def test_get_experiment_field_headers():
@pytest.mark.asyncio
async def test_get_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1931,7 +1999,7 @@ def test_get_experiment_flattened_error():
@pytest.mark.asyncio
async def test_get_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1960,7 +2028,7 @@ async def test_get_experiment_flattened_async():
@pytest.mark.asyncio
async def test_get_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2018,6 +2086,27 @@ def test_create_experiment(request_type, transport: str = "grpc"):
assert response.rollout_failure_reason == "rollout_failure_reason_value"
+def test_create_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_experiment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_experiment.CreateExperimentRequest()
+
+
def test_create_experiment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2085,6 +2174,35 @@ def test_create_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_experiment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+ )
+ response = await client.create_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_experiment.CreateExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_create_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2093,7 +2211,7 @@ async def test_create_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2108,23 +2226,27 @@ async def test_create_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2133,7 +2255,7 @@ async def test_create_experiment_async(
request_type=gcdc_experiment.CreateExperimentRequest,
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2211,7 +2333,7 @@ def test_create_experiment_field_headers():
@pytest.mark.asyncio
async def test_create_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2290,7 +2412,7 @@ def test_create_experiment_flattened_error():
@pytest.mark.asyncio
async def test_create_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2325,7 +2447,7 @@ async def test_create_experiment_flattened_async():
@pytest.mark.asyncio
async def test_create_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2384,6 +2506,27 @@ def test_update_experiment(request_type, transport: str = "grpc"):
assert response.rollout_failure_reason == "rollout_failure_reason_value"
+def test_update_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_experiment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_experiment.UpdateExperimentRequest()
+
+
def test_update_experiment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2447,6 +2590,35 @@ def test_update_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_experiment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+ )
+ response = await client.update_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_experiment.UpdateExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_update_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2455,7 +2627,7 @@ async def test_update_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2470,23 +2642,27 @@ async def test_update_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2495,7 +2671,7 @@ async def test_update_experiment_async(
request_type=gcdc_experiment.UpdateExperimentRequest,
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2573,7 +2749,7 @@ def test_update_experiment_field_headers():
@pytest.mark.asyncio
async def test_update_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2652,7 +2828,7 @@ def test_update_experiment_flattened_error():
@pytest.mark.asyncio
async def test_update_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2687,7 +2863,7 @@ async def test_update_experiment_flattened_async():
@pytest.mark.asyncio
async def test_update_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2735,6 +2911,27 @@ def test_delete_experiment(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_experiment), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.DeleteExperimentRequest()
+
+
def test_delete_experiment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2802,6 +2999,27 @@ def test_delete_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_experiment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.DeleteExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_delete_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2810,7 +3028,7 @@ async def test_delete_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2825,23 +3043,27 @@ async def test_delete_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2849,7 +3071,7 @@ async def test_delete_experiment_async(
transport: str = "grpc_asyncio", request_type=experiment.DeleteExperimentRequest
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2914,7 +3136,7 @@ def test_delete_experiment_field_headers():
@pytest.mark.asyncio
async def test_delete_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2986,7 +3208,7 @@ def test_delete_experiment_flattened_error():
@pytest.mark.asyncio
async def test_delete_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3015,7 +3237,7 @@ async def test_delete_experiment_flattened_async():
@pytest.mark.asyncio
async def test_delete_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3071,8 +3293,27 @@ def test_start_experiment(request_type, transport: str = "grpc"):
assert response.rollout_failure_reason == "rollout_failure_reason_value"
-def test_start_experiment_non_empty_request_with_auto_populated_field():
- # This test is a coverage failsafe to make sure that UUID4 fields are
+def test_start_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.start_experiment), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.start_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.StartExperimentRequest()
+
+
+def test_start_experiment_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3136,6 +3377,33 @@ def test_start_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_start_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.start_experiment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+ )
+ response = await client.start_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.StartExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_start_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3144,7 +3412,7 @@ async def test_start_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3159,23 +3427,27 @@ async def test_start_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.start_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.start_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.start_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3183,7 +3455,7 @@ async def test_start_experiment_async(
transport: str = "grpc_asyncio", request_type=experiment.StartExperimentRequest
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3257,7 +3529,7 @@ def test_start_experiment_field_headers():
@pytest.mark.asyncio
async def test_start_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3327,7 +3599,7 @@ def test_start_experiment_flattened_error():
@pytest.mark.asyncio
async def test_start_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3356,7 +3628,7 @@ async def test_start_experiment_flattened_async():
@pytest.mark.asyncio
async def test_start_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3412,6 +3684,25 @@ def test_stop_experiment(request_type, transport: str = "grpc"):
assert response.rollout_failure_reason == "rollout_failure_reason_value"
+def test_stop_experiment_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 = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.stop_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.StopExperimentRequest()
+
+
def test_stop_experiment_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3475,6 +3766,33 @@ def test_stop_experiment_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_stop_experiment_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+ )
+ response = await client.stop_experiment()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == experiment.StopExperimentRequest()
+
+
@pytest.mark.asyncio
async def test_stop_experiment_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3483,7 +3801,7 @@ async def test_stop_experiment_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3498,23 +3816,27 @@ async def test_stop_experiment_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.stop_experiment
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.stop_experiment(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.stop_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3522,7 +3844,7 @@ async def test_stop_experiment_async(
transport: str = "grpc_asyncio", request_type=experiment.StopExperimentRequest
):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3596,7 +3918,7 @@ def test_stop_experiment_field_headers():
@pytest.mark.asyncio
async def test_stop_experiment_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3666,7 +3988,7 @@ def test_stop_experiment_flattened_error():
@pytest.mark.asyncio
async def test_stop_experiment_flattened_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3695,7 +4017,7 @@ async def test_stop_experiment_flattened_async():
@pytest.mark.asyncio
async def test_stop_experiment_flattened_error_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3707,6 +4029,48 @@ async def test_stop_experiment_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ experiment.ListExperimentsRequest,
+ dict,
+ ],
+)
+def test_list_experiments_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = experiment.ListExperimentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = experiment.ListExperimentsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_experiments(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListExperimentsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_experiments_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3843,6 +4207,89 @@ def test_list_experiments_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_experiments_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
+ )
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "post_list_experiments"
+ ) as post, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_list_experiments"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = experiment.ListExperimentsRequest.pb(
+ experiment.ListExperimentsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = experiment.ListExperimentsResponse.to_json(
+ experiment.ListExperimentsResponse()
+ )
+
+ request = experiment.ListExperimentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = experiment.ListExperimentsResponse()
+
+ client.list_experiments(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_experiments_rest_bad_request(
+ transport: str = "rest", request_type=experiment.ListExperimentsRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_experiments(request)
+
+
def test_list_experiments_rest_flattened():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3967,28 +4414,78 @@ def test_list_experiments_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
-def test_get_experiment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ experiment.GetExperimentRequest,
+ dict,
+ ],
+)
+def test_get_experiment_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Ensure method has been cached
- assert client._transport.get_experiment in client._transport._wrapped_methods
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ request = request_type(**request_init)
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
)
- client._transport._wrapped_methods[client._transport.get_experiment] = mock_rpc
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_experiment(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, experiment.Experiment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == experiment.Experiment.State.DRAFT
+ assert response.rollout_failure_reason == "rollout_failure_reason_value"
+
+
+def test_get_experiment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_experiment in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_experiment] = mock_rpc
request = {}
client.get_experiment(request)
@@ -4086,6 +4583,89 @@ def test_get_experiment_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_experiment_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
+ )
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "post_get_experiment"
+ ) as post, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_get_experiment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = experiment.GetExperimentRequest.pb(
+ experiment.GetExperimentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = experiment.Experiment.to_json(
+ experiment.Experiment()
+ )
+
+ request = experiment.GetExperimentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = experiment.Experiment()
+
+ client.get_experiment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_experiment_rest_bad_request(
+ transport: str = "rest", request_type=experiment.GetExperimentRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_experiment(request)
+
+
def test_get_experiment_rest_flattened():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4145,158 +4725,172 @@ def test_get_experiment_rest_flattened_error(transport: str = "rest"):
)
-def test_create_experiment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.create_experiment in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.create_experiment
- ] = mock_rpc
-
- request = {}
- client.create_experiment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.create_experiment(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_create_experiment_rest_required_fields(
- request_type=gcdc_experiment.CreateExperimentRequest,
-):
- transport_class = transports.ExperimentsRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_experiment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_experiment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
+def test_get_experiment_rest_error():
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_experiment.Experiment()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.create_experiment(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_experiment_rest_unset_required_fields():
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_experiment._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "parent",
- "experiment",
- )
- )
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
-def test_create_experiment_rest_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_experiment.CreateExperimentRequest,
+ dict,
+ ],
+)
+def test_create_experiment_rest(request_type):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request_init["experiment"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "state": 1,
+ "definition": {
+ "condition": "condition_value",
+ "version_variants": {
+ "variants": [
+ {
+ "version": "version_value",
+ "traffic_allocation": 0.1892,
+ "is_control_group": True,
+ }
+ ]
+ },
+ },
+ "rollout_config": {
+ "rollout_steps": [
+ {
+ "display_name": "display_name_value",
+ "traffic_percent": 1583,
+ "min_duration": {"seconds": 751, "nanos": 543},
+ }
+ ],
+ "rollout_condition": "rollout_condition_value",
+ "failure_condition": "failure_condition_value",
+ },
+ "rollout_state": {
+ "step": "step_value",
+ "step_index": 1075,
+ "start_time": {"seconds": 751, "nanos": 543},
+ },
+ "rollout_failure_reason": "rollout_failure_reason_value",
+ "result": {
+ "version_metrics": [
+ {
+ "version": "version_value",
+ "metrics": [
+ {
+ "type_": 1,
+ "count_type": 1,
+ "ratio": 0.543,
+ "count": 0.553,
+ "confidence_interval": {
+ "confidence_level": 0.16690000000000002,
+ "ratio": 0.543,
+ "lower_bound": 0.1184,
+ "upper_bound": 0.1187,
+ },
+ }
+ ],
+ "session_count": 1420,
+ }
+ ],
+ "last_update_time": {},
+ },
+ "create_time": {},
+ "start_time": {},
+ "end_time": {},
+ "last_update_time": {},
+ "experiment_length": {},
+ "variants_history": [{"version_variants": {}, "update_time": {}}],
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_experiment.CreateExperimentRequest.meta.fields["experiment"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["experiment"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["experiment"][field])):
+ del request_init["experiment"][field][i][subfield]
+ else:
+ del request_init["experiment"][field][subfield]
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = gcdc_experiment.Experiment()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- experiment=gcdc_experiment.Experiment(name="name_value"),
+ return_value = gcdc_experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
)
- mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
@@ -4304,39 +4898,21 @@ def test_create_experiment_rest_flattened():
# Convert return value to protobuf type
return_value = gcdc_experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
+
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
+ response = client.create_experiment(request)
- client.create_experiment(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/experiments"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_experiment_rest_flattened_error(transport: str = "rest"):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_experiment(
- gcdc_experiment.CreateExperimentRequest(),
- parent="parent_value",
- experiment=gcdc_experiment.Experiment(name="name_value"),
- )
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_experiment.Experiment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == gcdc_experiment.Experiment.State.DRAFT
+ assert response.rollout_failure_reason == "rollout_failure_reason_value"
-def test_update_experiment_rest_use_cached_wrapped_rpc():
+def test_create_experiment_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -4350,7 +4926,7 @@ def test_update_experiment_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.update_experiment in client._transport._wrapped_methods
+ assert client._transport.create_experiment in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
@@ -4358,28 +4934,29 @@ def test_update_experiment_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.update_experiment
+ client._transport.create_experiment
] = mock_rpc
request = {}
- client.update_experiment(request)
+ client.create_experiment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_experiment(request)
+ client.create_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_update_experiment_rest_required_fields(
- request_type=gcdc_experiment.UpdateExperimentRequest,
+def test_create_experiment_rest_required_fields(
+ request_type=gcdc_experiment.CreateExperimentRequest,
):
transport_class = transports.ExperimentsRestTransport
request_init = {}
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -4390,19 +4967,21 @@ def test_update_experiment_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_experiment._get_unset_required_fields(jsonified_request)
+ ).create_experiment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ jsonified_request["parent"] = "parent_value"
+
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_experiment._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
+ ).create_experiment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4423,7 +5002,7 @@ def test_update_experiment_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "patch",
+ "method": "post",
"query_params": pb_request,
}
transcode_result["body"] = pb_request
@@ -4439,212 +5018,114 @@ def test_update_experiment_rest_required_fields(
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.update_experiment(request)
+ response = client.create_experiment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_update_experiment_rest_unset_required_fields():
+def test_create_experiment_rest_unset_required_fields():
transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.update_experiment._get_unset_required_fields({})
+ unset_fields = transport.create_experiment._get_unset_required_fields({})
assert set(unset_fields) == (
- set(("updateMask",))
+ set(())
& set(
(
+ "parent",
"experiment",
- "updateMask",
)
)
)
-def test_update_experiment_rest_flattened():
- client = ExperimentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_experiment_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_experiment.Experiment()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "experiment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- experiment=gcdc_experiment.Experiment(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_experiment(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{experiment.name=projects/*/locations/*/agents/*/environments/*/experiments/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_experiment_rest_flattened_error(transport: str = "rest"):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_experiment(
- gcdc_experiment.UpdateExperimentRequest(),
- experiment=gcdc_experiment.Experiment(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "post_create_experiment"
+ ) as post, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_create_experiment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_experiment.CreateExperimentRequest.pb(
+ gcdc_experiment.CreateExperimentRequest()
)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
-
-def test_delete_experiment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_experiment.Experiment.to_json(
+ gcdc_experiment.Experiment()
)
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.delete_experiment in client._transport._wrapped_methods
+ request = gcdc_experiment.CreateExperimentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_experiment.Experiment()
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.create_experiment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[
- client._transport.delete_experiment
- ] = mock_rpc
-
- request = {}
- client.delete_experiment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.delete_experiment(request)
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_delete_experiment_rest_required_fields(
- request_type=experiment.DeleteExperimentRequest,
+def test_create_experiment_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_experiment.CreateExperimentRequest
):
- transport_class = transports.ExperimentsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_experiment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_experiment._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = None
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "delete",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.delete_experiment(request)
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_experiment_rest_unset_required_fields():
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
+ }
+ request = request_type(**request_init)
- unset_fields = transport.delete_experiment._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_experiment(request)
-def test_delete_experiment_rest_flattened():
+def test_create_experiment_rest_flattened():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -4653,40 +5134,43 @@ def test_delete_experiment_rest_flattened():
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = gcdc_experiment.Experiment()
# get arguments that satisfy an http rule for this method
sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
}
# get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ parent="parent_value",
+ experiment=gcdc_experiment.Experiment(name="name_value"),
)
mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+ # Convert return value to protobuf type
+ return_value = gcdc_experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.delete_experiment(**mock_args)
+ client.create_experiment(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}"
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/environments/*}/experiments"
% client.transport._host,
args[1],
)
-def test_delete_experiment_rest_flattened_error(transport: str = "rest"):
+def test_create_experiment_rest_flattened_error(transport: str = "rest"):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4695,57 +5179,246 @@ def test_delete_experiment_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.delete_experiment(
- experiment.DeleteExperimentRequest(),
- name="name_value",
+ client.create_experiment(
+ gcdc_experiment.CreateExperimentRequest(),
+ parent="parent_value",
+ experiment=gcdc_experiment.Experiment(name="name_value"),
)
-def test_start_experiment_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+def test_create_experiment_rest_error():
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Ensure method has been cached
- assert client._transport.start_experiment in client._transport._wrapped_methods
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.start_experiment
- ] = mock_rpc
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_experiment.UpdateExperimentRequest,
+ dict,
+ ],
+)
+def test_update_experiment_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "experiment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ }
+ request_init["experiment"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "state": 1,
+ "definition": {
+ "condition": "condition_value",
+ "version_variants": {
+ "variants": [
+ {
+ "version": "version_value",
+ "traffic_allocation": 0.1892,
+ "is_control_group": True,
+ }
+ ]
+ },
+ },
+ "rollout_config": {
+ "rollout_steps": [
+ {
+ "display_name": "display_name_value",
+ "traffic_percent": 1583,
+ "min_duration": {"seconds": 751, "nanos": 543},
+ }
+ ],
+ "rollout_condition": "rollout_condition_value",
+ "failure_condition": "failure_condition_value",
+ },
+ "rollout_state": {
+ "step": "step_value",
+ "step_index": 1075,
+ "start_time": {"seconds": 751, "nanos": 543},
+ },
+ "rollout_failure_reason": "rollout_failure_reason_value",
+ "result": {
+ "version_metrics": [
+ {
+ "version": "version_value",
+ "metrics": [
+ {
+ "type_": 1,
+ "count_type": 1,
+ "ratio": 0.543,
+ "count": 0.553,
+ "confidence_interval": {
+ "confidence_level": 0.16690000000000002,
+ "ratio": 0.543,
+ "lower_bound": 0.1184,
+ "upper_bound": 0.1187,
+ },
+ }
+ ],
+ "session_count": 1420,
+ }
+ ],
+ "last_update_time": {},
+ },
+ "create_time": {},
+ "start_time": {},
+ "end_time": {},
+ "last_update_time": {},
+ "experiment_length": {},
+ "variants_history": [{"version_variants": {}, "update_time": {}}],
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_experiment.UpdateExperimentRequest.meta.fields["experiment"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["experiment"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["experiment"][field])):
+ del request_init["experiment"][field][i][subfield]
+ else:
+ del request_init["experiment"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_experiment(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_experiment.Experiment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == gcdc_experiment.Experiment.State.DRAFT
+ assert response.rollout_failure_reason == "rollout_failure_reason_value"
+
+
+def test_update_experiment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_experiment in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_experiment
+ ] = mock_rpc
request = {}
- client.start_experiment(request)
+ client.update_experiment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.start_experiment(request)
+ client.update_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_start_experiment_rest_required_fields(
- request_type=experiment.StartExperimentRequest,
+def test_update_experiment_rest_required_fields(
+ request_type=gcdc_experiment.UpdateExperimentRequest,
):
transport_class = transports.ExperimentsRestTransport
request_init = {}
- request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -4756,21 +5429,19 @@ def test_start_experiment_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).start_experiment._get_unset_required_fields(jsonified_request)
+ ).update_experiment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
-
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).start_experiment._get_unset_required_fields(jsonified_request)
+ ).update_experiment._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("update_mask",))
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4779,7 +5450,7 @@ def test_start_experiment_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = experiment.Experiment()
+ return_value = gcdc_experiment.Experiment()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -4791,7 +5462,7 @@ def test_start_experiment_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "post",
+ "method": "patch",
"query_params": pb_request,
}
transcode_result["body"] = pb_request
@@ -4801,47 +5472,143 @@ def test_start_experiment_rest_required_fields(
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
+ return_value = gcdc_experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.start_experiment(request)
+ response = client.update_experiment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_start_experiment_rest_unset_required_fields():
+def test_update_experiment_rest_unset_required_fields():
transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.start_experiment._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ unset_fields = transport.update_experiment._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("updateMask",))
+ & set(
+ (
+ "experiment",
+ "updateMask",
+ )
+ )
+ )
-def test_start_experiment_rest_flattened():
- client = ExperimentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_experiment_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = experiment.Experiment()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
-
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "post_update_experiment"
+ ) as post, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_update_experiment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_experiment.UpdateExperimentRequest.pb(
+ gcdc_experiment.UpdateExperimentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_experiment.Experiment.to_json(
+ gcdc_experiment.Experiment()
+ )
+
+ request = gcdc_experiment.UpdateExperimentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_experiment.Experiment()
+
+ client.update_experiment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_experiment_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_experiment.UpdateExperimentRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "experiment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_experiment(request)
+
+
+def test_update_experiment_rest_flattened():
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_experiment.Experiment()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "experiment": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ }
+
# get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ experiment=gcdc_experiment.Experiment(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
@@ -4849,25 +5616,25 @@ def test_start_experiment_rest_flattened():
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
+ return_value = gcdc_experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.start_experiment(**mock_args)
+ client.update_experiment(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:start"
+ "%s/v3beta1/{experiment.name=projects/*/locations/*/agents/*/environments/*/experiments/*}"
% client.transport._host,
args[1],
)
-def test_start_experiment_rest_flattened_error(transport: str = "rest"):
+def test_update_experiment_rest_flattened_error(transport: str = "rest"):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4876,13 +5643,57 @@ def test_start_experiment_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.start_experiment(
- experiment.StartExperimentRequest(),
- name="name_value",
+ client.update_experiment(
+ gcdc_experiment.UpdateExperimentRequest(),
+ experiment=gcdc_experiment.Experiment(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
-def test_stop_experiment_rest_use_cached_wrapped_rpc():
+def test_update_experiment_rest_error():
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ experiment.DeleteExperimentRequest,
+ dict,
+ ],
+)
+def test_delete_experiment_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_experiment(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_experiment_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -4896,30 +5707,32 @@ def test_stop_experiment_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.stop_experiment in client._transport._wrapped_methods
+ assert client._transport.delete_experiment in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.stop_experiment] = mock_rpc
+ client._transport._wrapped_methods[
+ client._transport.delete_experiment
+ ] = mock_rpc
request = {}
- client.stop_experiment(request)
+ client.delete_experiment(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.stop_experiment(request)
+ client.delete_experiment(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_stop_experiment_rest_required_fields(
- request_type=experiment.StopExperimentRequest,
+def test_delete_experiment_rest_required_fields(
+ request_type=experiment.DeleteExperimentRequest,
):
transport_class = transports.ExperimentsRestTransport
@@ -4935,7 +5748,7 @@ def test_stop_experiment_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).stop_experiment._get_unset_required_fields(jsonified_request)
+ ).delete_experiment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
@@ -4944,7 +5757,7 @@ def test_stop_experiment_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).stop_experiment._get_unset_required_fields(jsonified_request)
+ ).delete_experiment._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
@@ -4958,7 +5771,7 @@ def test_stop_experiment_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = experiment.Experiment()
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -4970,1406 +5783,183 @@ def test_stop_experiment_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "post",
+ "method": "delete",
"query_params": pb_request,
}
- transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
+ json_return_value = ""
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.stop_experiment(request)
+ response = client.delete_experiment(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_stop_experiment_rest_unset_required_fields():
+def test_delete_experiment_rest_unset_required_fields():
transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.stop_experiment._get_unset_required_fields({})
+ unset_fields = transport.delete_experiment._get_unset_required_fields({})
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_stop_experiment_rest_flattened():
- client = ExperimentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_experiment_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
)
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_delete_experiment"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = experiment.DeleteExperimentRequest.pb(
+ experiment.DeleteExperimentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = experiment.Experiment()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
+ request = experiment.DeleteExperimentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
+ client.delete_experiment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ pre.assert_called_once()
- client.stop_experiment(**mock_args)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:stop"
- % client.transport._host,
- args[1],
- )
-
-
-def test_stop_experiment_rest_flattened_error(transport: str = "rest"):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.stop_experiment(
- experiment.StopExperimentRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ExperimentsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ExperimentsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ExperimentsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ExperimentsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = ExperimentsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ExperimentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.ExperimentsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.ExperimentsGrpcTransport,
- transports.ExperimentsGrpcAsyncIOTransport,
- transports.ExperimentsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = ExperimentsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_experiments_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_experiments), "__call__") as call:
- call.return_value = experiment.ListExperimentsResponse()
- client.list_experiments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.ListExperimentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_experiment), "__call__") as call:
- call.return_value = experiment.Experiment()
- client.get_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.GetExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_experiment), "__call__"
- ) as call:
- call.return_value = gcdc_experiment.Experiment()
- client.create_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.CreateExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_experiment), "__call__"
- ) as call:
- call.return_value = gcdc_experiment.Experiment()
- client.update_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.UpdateExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_experiment), "__call__"
- ) as call:
- call.return_value = None
- client.delete_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.DeleteExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_start_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.start_experiment), "__call__") as call:
- call.return_value = experiment.Experiment()
- client.start_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StartExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_stop_experiment_empty_call_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call:
- call.return_value = experiment.Experiment()
- client.stop_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StopExperimentRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ExperimentsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_experiments_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_experiments), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- experiment.ListExperimentsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_experiments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.ListExperimentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_experiment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
- )
- await client.get_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.GetExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_experiment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
- )
- await client.create_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.CreateExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_experiment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
- )
- await client.update_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.UpdateExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_experiment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.DeleteExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_start_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.start_experiment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
- )
- await client.start_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StartExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_stop_experiment_empty_call_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
- )
- await client.stop_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StopExperimentRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = ExperimentsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_experiments_rest_bad_request(
- request_type=experiment.ListExperimentsRequest,
-):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_experiments(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- experiment.ListExperimentsRequest,
- dict,
- ],
-)
-def test_list_experiments_rest_call_success(request_type):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = experiment.ListExperimentsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = experiment.ListExperimentsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_experiments(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListExperimentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_experiments_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "post_list_experiments"
- ) as post, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_list_experiments"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = experiment.ListExperimentsRequest.pb(
- experiment.ListExperimentsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = experiment.ListExperimentsResponse.to_json(
- experiment.ListExperimentsResponse()
- )
- req.return_value.content = return_value
-
- request = experiment.ListExperimentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = experiment.ListExperimentsResponse()
-
- client.list_experiments(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_experiment_rest_bad_request(request_type=experiment.GetExperimentRequest):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_experiment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- experiment.GetExperimentRequest,
- dict,
- ],
-)
-def test_get_experiment_rest_call_success(request_type):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_experiment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, experiment.Experiment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == experiment.Experiment.State.DRAFT
- assert response.rollout_failure_reason == "rollout_failure_reason_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_experiment_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "post_get_experiment"
- ) as post, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_get_experiment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = experiment.GetExperimentRequest.pb(
- experiment.GetExperimentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = experiment.Experiment.to_json(experiment.Experiment())
- req.return_value.content = return_value
-
- request = experiment.GetExperimentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = experiment.Experiment()
-
- client.get_experiment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_experiment_rest_bad_request(
- request_type=gcdc_experiment.CreateExperimentRequest,
-):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_experiment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_experiment.CreateExperimentRequest,
- dict,
- ],
-)
-def test_create_experiment_rest_call_success(request_type):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/environments/sample4"
- }
- request_init["experiment"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "description": "description_value",
- "state": 1,
- "definition": {
- "condition": "condition_value",
- "version_variants": {
- "variants": [
- {
- "version": "version_value",
- "traffic_allocation": 0.1892,
- "is_control_group": True,
- }
- ]
- },
- },
- "rollout_config": {
- "rollout_steps": [
- {
- "display_name": "display_name_value",
- "traffic_percent": 1583,
- "min_duration": {"seconds": 751, "nanos": 543},
- }
- ],
- "rollout_condition": "rollout_condition_value",
- "failure_condition": "failure_condition_value",
- },
- "rollout_state": {
- "step": "step_value",
- "step_index": 1075,
- "start_time": {"seconds": 751, "nanos": 543},
- },
- "rollout_failure_reason": "rollout_failure_reason_value",
- "result": {
- "version_metrics": [
- {
- "version": "version_value",
- "metrics": [
- {
- "type_": 1,
- "count_type": 1,
- "ratio": 0.543,
- "count": 0.553,
- "confidence_interval": {
- "confidence_level": 0.16690000000000002,
- "ratio": 0.543,
- "lower_bound": 0.1184,
- "upper_bound": 0.1187,
- },
- }
- ],
- "session_count": 1420,
- }
- ],
- "last_update_time": {},
- },
- "create_time": {},
- "start_time": {},
- "end_time": {},
- "last_update_time": {},
- "experiment_length": {},
- "variants_history": [{"version_variants": {}, "update_time": {}}],
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_experiment.CreateExperimentRequest.meta.fields["experiment"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["experiment"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["experiment"][field])):
- del request_init["experiment"][field][i][subfield]
- else:
- del request_init["experiment"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_experiment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_experiment.Experiment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == gcdc_experiment.Experiment.State.DRAFT
- assert response.rollout_failure_reason == "rollout_failure_reason_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_experiment_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "post_create_experiment"
- ) as post, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_create_experiment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_experiment.CreateExperimentRequest.pb(
- gcdc_experiment.CreateExperimentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_experiment.Experiment.to_json(gcdc_experiment.Experiment())
- req.return_value.content = return_value
-
- request = gcdc_experiment.CreateExperimentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_experiment.Experiment()
-
- client.create_experiment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_experiment_rest_bad_request(
- request_type=gcdc_experiment.UpdateExperimentRequest,
-):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "experiment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_experiment(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_experiment.UpdateExperimentRequest,
- dict,
- ],
-)
-def test_update_experiment_rest_call_success(request_type):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "experiment": {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- }
- request_init["experiment"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5",
- "display_name": "display_name_value",
- "description": "description_value",
- "state": 1,
- "definition": {
- "condition": "condition_value",
- "version_variants": {
- "variants": [
- {
- "version": "version_value",
- "traffic_allocation": 0.1892,
- "is_control_group": True,
- }
- ]
- },
- },
- "rollout_config": {
- "rollout_steps": [
- {
- "display_name": "display_name_value",
- "traffic_percent": 1583,
- "min_duration": {"seconds": 751, "nanos": 543},
- }
- ],
- "rollout_condition": "rollout_condition_value",
- "failure_condition": "failure_condition_value",
- },
- "rollout_state": {
- "step": "step_value",
- "step_index": 1075,
- "start_time": {"seconds": 751, "nanos": 543},
- },
- "rollout_failure_reason": "rollout_failure_reason_value",
- "result": {
- "version_metrics": [
- {
- "version": "version_value",
- "metrics": [
- {
- "type_": 1,
- "count_type": 1,
- "ratio": 0.543,
- "count": 0.553,
- "confidence_interval": {
- "confidence_level": 0.16690000000000002,
- "ratio": 0.543,
- "lower_bound": 0.1184,
- "upper_bound": 0.1187,
- },
- }
- ],
- "session_count": 1420,
- }
- ],
- "last_update_time": {},
- },
- "create_time": {},
- "start_time": {},
- "end_time": {},
- "last_update_time": {},
- "experiment_length": {},
- "variants_history": [{"version_variants": {}, "update_time": {}}],
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_experiment.UpdateExperimentRequest.meta.fields["experiment"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["experiment"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
+def test_delete_experiment_rest_bad_request(
+ transport: str = "rest", request_type=experiment.DeleteExperimentRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["experiment"][field])):
- del request_init["experiment"][field][i][subfield]
- else:
- del request_init["experiment"][field][subfield]
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
request = request_type(**request_init)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_experiment(request)
+
+
+def test_delete_experiment_rest_flattened():
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = gcdc_experiment.Experiment(
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
)
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.update_experiment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_experiment.Experiment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == gcdc_experiment.Experiment.State.DRAFT
- assert response.rollout_failure_reason == "rollout_failure_reason_value"
+ client.delete_experiment(**mock_args)
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_experiment_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "post_update_experiment"
- ) as post, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_update_experiment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_experiment.UpdateExperimentRequest.pb(
- gcdc_experiment.UpdateExperimentRequest()
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}"
+ % client.transport._host,
+ args[1],
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_experiment.Experiment.to_json(gcdc_experiment.Experiment())
- req.return_value.content = return_value
- request = gcdc_experiment.UpdateExperimentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_experiment.Experiment()
+def test_delete_experiment_rest_flattened_error(transport: str = "rest"):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- client.update_experiment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_experiment(
+ experiment.DeleteExperimentRequest(),
+ name="name_value",
)
- pre.assert_called_once()
- post.assert_called_once()
-
-def test_delete_experiment_rest_bad_request(
- request_type=experiment.DeleteExperimentRequest,
-):
+def test_delete_experiment_rest_error():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_experiment(request)
@pytest.mark.parametrize(
"request_type",
[
- experiment.DeleteExperimentRequest,
+ experiment.StartExperimentRequest,
dict,
],
)
-def test_delete_experiment_rest_call_success(request_type):
+def test_start_experiment_rest(request_type):
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -6381,142 +5971,154 @@ def test_delete_experiment_rest_call_success(request_type):
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_experiment(request)
+ response = client.start_experiment(request)
# Establish that the response is the type that we expect.
- assert response is None
+ assert isinstance(response, experiment.Experiment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == experiment.Experiment.State.DRAFT
+ assert response.rollout_failure_reason == "rollout_failure_reason_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_experiment_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
+def test_start_experiment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_delete_experiment"
- ) as pre:
- pre.assert_not_called()
- pb_message = experiment.DeleteExperimentRequest.pb(
- experiment.DeleteExperimentRequest()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.start_experiment in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+ client._transport._wrapped_methods[
+ client._transport.start_experiment
+ ] = mock_rpc
+
+ request = {}
+ client.start_experiment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.start_experiment(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_start_experiment_rest_required_fields(
+ request_type=experiment.StartExperimentRequest,
+):
+ transport_class = transports.ExperimentsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
+ # verify fields with default values are dropped
- request = experiment.DeleteExperimentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).start_experiment._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
- client.delete_experiment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
+ # verify required fields with default values are now present
- pre.assert_called_once()
+ jsonified_request["name"] = "name_value"
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).start_experiment._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-def test_start_experiment_rest_bad_request(
- request_type=experiment.StartExperimentRequest,
-):
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
request = request_type(**request_init)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.start_experiment(request)
+ # Designate an appropriate value for the returned response.
+ return_value = experiment.Experiment()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+ response_value = Response()
+ response_value.status_code = 200
-@pytest.mark.parametrize(
- "request_type",
- [
- experiment.StartExperimentRequest,
- dict,
- ],
-)
-def test_start_experiment_rest_call_success(request_type):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- request = request_type(**request_init)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = experiment.Experiment(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
- )
+ response = client.start_experiment(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = experiment.Experiment.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.start_experiment(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, experiment.Experiment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == experiment.Experiment.State.DRAFT
- assert response.rollout_failure_reason == "rollout_failure_reason_value"
+def test_start_experiment_rest_unset_required_fields():
+ transport = transports.ExperimentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.start_experiment._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -6528,7 +6130,6 @@ def test_start_experiment_rest_interceptors(null_interceptor):
else transports.ExperimentsRestInterceptor(),
)
client = ExperimentsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -6550,10 +6151,12 @@ def test_start_experiment_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = experiment.Experiment.to_json(experiment.Experiment())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = experiment.Experiment.to_json(
+ experiment.Experiment()
+ )
request = experiment.StartExperimentRequest()
metadata = [
@@ -6575,12 +6178,14 @@ def test_start_experiment_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_stop_experiment_rest_bad_request(
- request_type=experiment.StopExperimentRequest,
+def test_start_experiment_rest_bad_request(
+ transport: str = "rest", request_type=experiment.StartExperimentRequest
):
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
"name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
@@ -6592,565 +6197,500 @@ def test_stop_experiment_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.stop_experiment(request)
+ client.start_experiment(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- experiment.StopExperimentRequest,
- dict,
- ],
-)
-def test_stop_experiment_rest_call_success(request_type):
+def test_start_experiment_rest_flattened():
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = experiment.Experiment(
+ return_value = experiment.Experiment()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=experiment.Experiment.State.DRAFT,
- rollout_failure_reason="rollout_failure_reason_value",
)
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.stop_experiment(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, experiment.Experiment)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == experiment.Experiment.State.DRAFT
- assert response.rollout_failure_reason == "rollout_failure_reason_value"
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_stop_experiment_rest_interceptors(null_interceptor):
- transport = transports.ExperimentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.ExperimentsRestInterceptor(),
- )
- client = ExperimentsClient(transport=transport)
+ client.start_experiment(**mock_args)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ExperimentsRestInterceptor, "post_stop_experiment"
- ) as post, mock.patch.object(
- transports.ExperimentsRestInterceptor, "pre_stop_experiment"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = experiment.StopExperimentRequest.pb(
- experiment.StopExperimentRequest()
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:start"
+ % client.transport._host,
+ args[1],
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = experiment.Experiment.to_json(experiment.Experiment())
- req.return_value.content = return_value
- request = experiment.StopExperimentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = experiment.Experiment()
+def test_start_experiment_rest_flattened_error(transport: str = "rest"):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- client.stop_experiment(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.start_experiment(
+ experiment.StartExperimentRequest(),
+ name="name_value",
)
- pre.assert_called_once()
- post.assert_called_once()
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_start_experiment_rest_error():
client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.GetLocationRequest,
+ experiment.StopExperimentRequest,
dict,
],
)
-def test_get_location_rest(request_type):
+def test_stop_experiment_rest(request_type):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = experiment.Experiment(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=experiment.Experiment.State.DRAFT,
+ rollout_failure_reason="rollout_failure_reason_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.get_location(request)
+ response = client.stop_experiment(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ assert isinstance(response, experiment.Experiment)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == experiment.Experiment.State.DRAFT
+ assert response.rollout_failure_reason == "rollout_failure_reason_value"
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
+def test_stop_experiment_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.stop_experiment in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.stop_experiment] = mock_rpc
+
+ request = {}
+ client.stop_experiment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.stop_experiment(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_stop_experiment_rest_required_fields(
+ request_type=experiment.StopExperimentRequest,
):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport_class = transports.ExperimentsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).stop_experiment._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).stop_experiment._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = experiment.Experiment()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
- req.return_value = response_value
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- response = client.list_locations(request)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ response = client.stop_experiment(request)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+
+def test_stop_experiment_rest_unset_required_fields():
+ transport = transports.ExperimentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ unset_fields = transport.stop_experiment._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = ExperimentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_stop_experiment_rest_interceptors(null_interceptor):
+ transport = transports.ExperimentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.ExperimentsRestInterceptor(),
)
+ client = ExperimentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "post_stop_experiment"
+ ) as post, mock.patch.object(
+ transports.ExperimentsRestInterceptor, "pre_stop_experiment"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = experiment.StopExperimentRequest.pb(
+ experiment.StopExperimentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = experiment.Experiment.to_json(
+ experiment.Experiment()
+ )
- req.return_value = response_value
+ request = experiment.StopExperimentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = experiment.Experiment()
- response = client.cancel_operation(request)
+ client.stop_experiment(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert response is None
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
+def test_stop_experiment_rest_bad_request(
+ transport: str = "rest", request_type=experiment.StopExperimentRequest
):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_operation(request)
+ client.stop_experiment(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
+def test_stop_experiment_rest_flattened():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ return_value = experiment.Experiment()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/environments/sample4/experiments/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = experiment.Experiment.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+ client.stop_experiment(**mock_args)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/environments/*/experiments/*}:stop"
+ % client.transport._host,
+ args[1],
+ )
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+def test_stop_experiment_rest_flattened_error(transport: str = "rest"):
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.stop_experiment(
+ experiment.StopExperimentRequest(),
+ name="name_value",
+ )
-def test_initialize_client_w_rest():
+def test_stop_experiment_rest_error():
client = ExperimentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_experiments_empty_call_rest():
- client = ExperimentsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_experiments), "__call__") as call:
- client.list_experiments(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.ListExperimentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_experiment_empty_call_rest():
- client = ExperimentsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = ExperimentsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_experiment), "__call__") as call:
- client.get_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.GetExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_experiment_empty_call_rest():
- client = ExperimentsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ExperimentsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_experiment), "__call__"
- ) as call:
- client.create_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.CreateExperimentRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ExperimentsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_experiment_empty_call_rest():
- client = ExperimentsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_experiment), "__call__"
- ) as call:
- client.update_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_experiment.UpdateExperimentRequest()
-
- assert args[0] == request_msg
+ with pytest.raises(ValueError):
+ client = ExperimentsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_experiment_empty_call_rest():
- client = ExperimentsClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_experiment), "__call__"
- ) as call:
- client.delete_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.DeleteExperimentRequest()
-
- assert args[0] == request_msg
+ client = ExperimentsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_start_experiment_empty_call_rest():
- client = ExperimentsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ExperimentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.start_experiment), "__call__") as call:
- client.start_experiment(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StartExperimentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_stop_experiment_empty_call_rest():
- client = ExperimentsClient(
+ transport = transports.ExperimentsGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call:
- client.stop_experiment(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = experiment.StopExperimentRequest()
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ExperimentsGrpcTransport,
+ transports.ExperimentsGrpcAsyncIOTransport,
+ transports.ExperimentsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = ExperimentsClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -7687,115 +7227,415 @@ def test_parse_common_billing_account_path():
}
path = ExperimentsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = ExperimentsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = ExperimentsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = ExperimentsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = ExperimentsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExperimentsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = ExperimentsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = ExperimentsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExperimentsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = ExperimentsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = ExperimentsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = ExperimentsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ExperimentsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ExperimentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ExperimentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ExperimentsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = ExperimentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ExperimentsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = ExperimentsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ExperimentsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = ExperimentsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = ExperimentsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = ExperimentsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ExperimentsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = ExperimentsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ExperimentsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ExperimentsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = ExperimentsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = ExperimentsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.ExperimentsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.ExperimentsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = ExperimentsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -7825,7 +7665,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7878,7 +7718,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7923,7 +7763,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -7964,7 +7804,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8019,7 +7859,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -8066,7 +7906,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -8109,7 +7949,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8164,7 +8004,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -8211,7 +8051,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -8254,7 +8094,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8309,7 +8149,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -8356,7 +8196,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8399,7 +8239,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8451,7 +8291,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = ExperimentsAsyncClient(credentials=async_anonymous_credentials())
+ client = ExperimentsAsyncClient(credentials=ga_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.
@@ -8497,7 +8337,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8513,41 +8353,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = ExperimentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = ExperimentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = ExperimentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py
index 24c088a94b2d..d99ff930d96d 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -65,8 +47,16 @@
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.flows import (
FlowsAsyncClient,
@@ -91,24 +81,10 @@
from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1126,7 +1102,6 @@ def test_create_flow(request_type, transport: str = "grpc"):
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
response = client.create_flow(request)
@@ -1142,7 +1117,25 @@ def test_create_flow(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+
+
+def test_create_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_flow.CreateFlowRequest()
def test_create_flow_non_empty_request_with_auto_populated_field():
@@ -1210,6 +1203,32 @@ def test_create_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_flow), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.create_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_flow.CreateFlowRequest()
+
+
@pytest.mark.asyncio
async def test_create_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1218,7 +1237,7 @@ async def test_create_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1233,23 +1252,27 @@ async def test_create_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1257,7 +1280,7 @@ async def test_create_flow_async(
transport: str = "grpc_asyncio", request_type=gcdc_flow.CreateFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1274,7 +1297,6 @@ async def test_create_flow_async(
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
)
response = await client.create_flow(request)
@@ -1291,7 +1313,6 @@ async def test_create_flow_async(
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
@pytest.mark.asyncio
@@ -1331,7 +1352,7 @@ def test_create_flow_field_headers():
@pytest.mark.asyncio
async def test_create_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1404,7 +1425,7 @@ def test_create_flow_flattened_error():
@pytest.mark.asyncio
async def test_create_flow_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1435,7 +1456,7 @@ async def test_create_flow_flattened_async():
@pytest.mark.asyncio
async def test_create_flow_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1481,6 +1502,25 @@ def test_delete_flow(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.DeleteFlowRequest()
+
+
def test_delete_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1544,6 +1584,25 @@ def test_delete_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_flow), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.DeleteFlowRequest()
+
+
@pytest.mark.asyncio
async def test_delete_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1552,7 +1611,7 @@ async def test_delete_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1567,23 +1626,27 @@ async def test_delete_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1591,7 +1654,7 @@ async def test_delete_flow_async(
transport: str = "grpc_asyncio", request_type=flow.DeleteFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1652,7 +1715,7 @@ def test_delete_flow_field_headers():
@pytest.mark.asyncio
async def test_delete_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1720,7 +1783,7 @@ def test_delete_flow_flattened_error():
@pytest.mark.asyncio
async def test_delete_flow_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1747,7 +1810,7 @@ async def test_delete_flow_flattened_async():
@pytest.mark.asyncio
async def test_delete_flow_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1795,6 +1858,25 @@ def test_list_flows(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_flows_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_flows), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_flows()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ListFlowsRequest()
+
+
def test_list_flows_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1862,13 +1944,36 @@ def test_list_flows_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_flows_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_flows), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ flow.ListFlowsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_flows()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ListFlowsRequest()
+
+
@pytest.mark.asyncio
async def test_list_flows_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1883,23 +1988,27 @@ async def test_list_flows_async_use_cached_wrapped_rpc(transport: str = "grpc_as
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_flows
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_flows(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_flows(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1907,7 +2016,7 @@ async def test_list_flows_async(
transport: str = "grpc_asyncio", request_type=flow.ListFlowsRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1973,7 +2082,7 @@ def test_list_flows_field_headers():
@pytest.mark.asyncio
async def test_list_flows_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2043,7 +2152,7 @@ def test_list_flows_flattened_error():
@pytest.mark.asyncio
async def test_list_flows_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2072,7 +2181,7 @@ async def test_list_flows_flattened_async():
@pytest.mark.asyncio
async def test_list_flows_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2122,16 +2231,12 @@ def test_list_flows_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_flows(request={}, retry=retry, timeout=timeout)
+ pager = client.list_flows(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -2182,7 +2287,7 @@ def test_list_flows_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_flows_async_pager():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2232,7 +2337,7 @@ async def test_list_flows_async_pager():
@pytest.mark.asyncio
async def test_list_flows_async_pages():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2303,7 +2408,6 @@ def test_get_flow(request_type, transport: str = "grpc"):
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
response = client.get_flow(request)
@@ -2319,7 +2423,25 @@ def test_get_flow(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+
+
+def test_get_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.GetFlowRequest()
def test_get_flow_non_empty_request_with_auto_populated_field():
@@ -2387,13 +2509,39 @@ def test_get_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_flow), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.get_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.GetFlowRequest()
+
+
@pytest.mark.asyncio
async def test_get_flow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2408,23 +2556,27 @@ async def test_get_flow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2432,7 +2584,7 @@ async def test_get_flow_async(
transport: str = "grpc_asyncio", request_type=flow.GetFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2449,7 +2601,6 @@ async def test_get_flow_async(
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
)
response = await client.get_flow(request)
@@ -2466,7 +2617,6 @@ async def test_get_flow_async(
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
@pytest.mark.asyncio
@@ -2506,7 +2656,7 @@ def test_get_flow_field_headers():
@pytest.mark.asyncio
async def test_get_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2574,7 +2724,7 @@ def test_get_flow_flattened_error():
@pytest.mark.asyncio
async def test_get_flow_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2601,7 +2751,7 @@ async def test_get_flow_flattened_async():
@pytest.mark.asyncio
async def test_get_flow_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2638,7 +2788,6 @@ def test_update_flow(request_type, transport: str = "grpc"):
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
response = client.update_flow(request)
@@ -2654,7 +2803,25 @@ def test_update_flow(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+
+
+def test_update_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_flow.UpdateFlowRequest()
def test_update_flow_non_empty_request_with_auto_populated_field():
@@ -2720,6 +2887,32 @@ def test_update_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_flow), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.update_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_flow.UpdateFlowRequest()
+
+
@pytest.mark.asyncio
async def test_update_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2728,7 +2921,7 @@ async def test_update_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2743,23 +2936,27 @@ async def test_update_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2767,7 +2964,7 @@ async def test_update_flow_async(
transport: str = "grpc_asyncio", request_type=gcdc_flow.UpdateFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2784,7 +2981,6 @@ async def test_update_flow_async(
display_name="display_name_value",
description="description_value",
transition_route_groups=["transition_route_groups_value"],
- locked=True,
)
)
response = await client.update_flow(request)
@@ -2801,7 +2997,6 @@ async def test_update_flow_async(
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
@pytest.mark.asyncio
@@ -2841,7 +3036,7 @@ def test_update_flow_field_headers():
@pytest.mark.asyncio
async def test_update_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2914,7 +3109,7 @@ def test_update_flow_flattened_error():
@pytest.mark.asyncio
async def test_update_flow_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2945,7 +3140,7 @@ async def test_update_flow_flattened_async():
@pytest.mark.asyncio
async def test_update_flow_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2991,6 +3186,25 @@ def test_train_flow(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_train_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.train_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.train_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.TrainFlowRequest()
+
+
def test_train_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3047,9 +3261,8 @@ def test_train_flow_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.train_flow(request)
@@ -3060,12 +3273,33 @@ def test_train_flow_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_train_flow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
+async def test_train_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.train_flow), "__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.train_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.TrainFlowRequest()
+
+
+@pytest.mark.asyncio
+async def test_train_flow_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3080,28 +3314,31 @@ async def test_train_flow_async_use_cached_wrapped_rpc(transport: str = "grpc_as
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.train_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.train_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.train_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3109,7 +3346,7 @@ async def test_train_flow_async(
transport: str = "grpc_asyncio", request_type=flow.TrainFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3172,7 +3409,7 @@ def test_train_flow_field_headers():
@pytest.mark.asyncio
async def test_train_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3242,7 +3479,7 @@ def test_train_flow_flattened_error():
@pytest.mark.asyncio
async def test_train_flow_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3271,7 +3508,7 @@ async def test_train_flow_flattened_async():
@pytest.mark.asyncio
async def test_train_flow_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3319,6 +3556,25 @@ def test_validate_flow(request_type, transport: str = "grpc"):
assert response.name == "name_value"
+def test_validate_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.validate_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.validate_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ValidateFlowRequest()
+
+
def test_validate_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3384,6 +3640,29 @@ def test_validate_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_validate_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.validate_flow), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ flow.FlowValidationResult(
+ name="name_value",
+ )
+ )
+ response = await client.validate_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ValidateFlowRequest()
+
+
@pytest.mark.asyncio
async def test_validate_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3392,7 +3671,7 @@ async def test_validate_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3407,23 +3686,27 @@ async def test_validate_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.validate_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.validate_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.validate_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3431,7 +3714,7 @@ async def test_validate_flow_async(
transport: str = "grpc_asyncio", request_type=flow.ValidateFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3497,7 +3780,7 @@ def test_validate_flow_field_headers():
@pytest.mark.asyncio
async def test_validate_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3564,6 +3847,27 @@ def test_get_flow_validation_result(request_type, transport: str = "grpc"):
assert response.name == "name_value"
+def test_get_flow_validation_result_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_flow_validation_result), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_flow_validation_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.GetFlowValidationResultRequest()
+
+
def test_get_flow_validation_result_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3636,6 +3940,31 @@ def test_get_flow_validation_result_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_flow_validation_result_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_flow_validation_result), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ flow.FlowValidationResult(
+ name="name_value",
+ )
+ )
+ response = await client.get_flow_validation_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.GetFlowValidationResultRequest()
+
+
@pytest.mark.asyncio
async def test_get_flow_validation_result_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3644,7 +3973,7 @@ async def test_get_flow_validation_result_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3659,23 +3988,27 @@ async def test_get_flow_validation_result_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_flow_validation_result
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_flow_validation_result(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_flow_validation_result(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3683,7 +4016,7 @@ async def test_get_flow_validation_result_async(
transport: str = "grpc_asyncio", request_type=flow.GetFlowValidationResultRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3753,7 +4086,7 @@ def test_get_flow_validation_result_field_headers():
@pytest.mark.asyncio
async def test_get_flow_validation_result_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3827,7 +4160,7 @@ def test_get_flow_validation_result_flattened_error():
@pytest.mark.asyncio
async def test_get_flow_validation_result_flattened_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3858,7 +4191,7 @@ async def test_get_flow_validation_result_flattened_async():
@pytest.mark.asyncio
async def test_get_flow_validation_result_flattened_error_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3903,6 +4236,25 @@ def test_import_flow(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_import_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.import_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.import_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ImportFlowRequest()
+
+
def test_import_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3961,9 +4313,8 @@ def test_import_flow_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.import_flow(request)
@@ -3973,6 +4324,27 @@ def test_import_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_import_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.import_flow), "__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.import_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ImportFlowRequest()
+
+
@pytest.mark.asyncio
async def test_import_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3981,7 +4353,7 @@ async def test_import_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3996,28 +4368,31 @@ async def test_import_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.import_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.import_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.import_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4025,7 +4400,7 @@ async def test_import_flow_async(
transport: str = "grpc_asyncio", request_type=flow.ImportFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4088,7 +4463,7 @@ def test_import_flow_field_headers():
@pytest.mark.asyncio
async def test_import_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4150,6 +4525,25 @@ def test_export_flow(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_flow_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 = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_flow), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ExportFlowRequest()
+
+
def test_export_flow_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4208,9 +4602,8 @@ def test_export_flow_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_flow(request)
@@ -4220,6 +4613,27 @@ def test_export_flow_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_flow_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_flow), "__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.export_flow()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == flow.ExportFlowRequest()
+
+
@pytest.mark.asyncio
async def test_export_flow_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4228,7 +4642,7 @@ async def test_export_flow_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4243,28 +4657,31 @@ async def test_export_flow_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_flow
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_flow(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4272,7 +4689,7 @@ async def test_export_flow_async(
transport: str = "grpc_asyncio", request_type=flow.ExportFlowRequest
):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4335,7 +4752,7 @@ def test_export_flow_field_headers():
@pytest.mark.asyncio
async def test_export_flow_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4364,1586 +4781,261 @@ async def test_export_flow_field_headers_async():
) in kw["metadata"]
-def test_create_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.create_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.create_flow] = mock_rpc
-
- request = {}
- client.create_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.create_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_create_flow_rest_required_fields(request_type=gcdc_flow.CreateFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_flow.CreateFlowRequest,
+ dict,
+ ],
+)
+def test_create_flow_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_flow._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.create_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_flow._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("languageCode",))
- & set(
- (
- "parent",
- "flow",
- )
- )
- )
-
-
-def test_create_flow_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- flow=gcdc_flow.Flow(name="name_value"),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.create_flow(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/flows"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_flow_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_flow(
- gcdc_flow.CreateFlowRequest(),
- parent="parent_value",
- flow=gcdc_flow.Flow(name="name_value"),
- )
-
-
-def test_delete_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.delete_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.delete_flow] = mock_rpc
-
- request = {}
- client.delete_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.delete_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_delete_flow_rest_required_fields(request_type=flow.DeleteFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_flow._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("force",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = None
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "delete",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.delete_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(("force",)) & set(("name",)))
-
-
-def test_delete_flow_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_flow(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_flow_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_flow(
- flow.DeleteFlowRequest(),
- name="name_value",
- )
-
-
-def test_list_flows_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.list_flows in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.list_flows] = mock_rpc
-
- request = {}
- client.list_flows(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.list_flows(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_list_flows_rest_required_fields(request_type=flow.ListFlowsRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_flows._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_flows._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "language_code",
- "page_size",
- "page_token",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = flow.ListFlowsResponse()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = flow.ListFlowsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.list_flows(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_list_flows_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.list_flows._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "languageCode",
- "pageSize",
- "pageToken",
- )
- )
- & set(("parent",))
- )
-
-
-def test_list_flows_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.ListFlowsResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = flow.ListFlowsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.list_flows(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/flows"
- % client.transport._host,
- args[1],
- )
-
-
-def test_list_flows_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_flows(
- flow.ListFlowsRequest(),
- parent="parent_value",
- )
-
-
-def test_list_flows_rest_pager(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- flow.ListFlowsResponse(
- flows=[
- flow.Flow(),
- flow.Flow(),
- flow.Flow(),
- ],
- next_page_token="abc",
- ),
- flow.ListFlowsResponse(
- flows=[],
- next_page_token="def",
- ),
- flow.ListFlowsResponse(
- flows=[
- flow.Flow(),
- ],
- next_page_token="ghi",
- ),
- flow.ListFlowsResponse(
- flows=[
- flow.Flow(),
- flow.Flow(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(flow.ListFlowsResponse.to_json(x) for x in response)
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-
- pager = client.list_flows(request=sample_request)
-
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, flow.Flow) for i in results)
-
- pages = list(client.list_flows(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-def test_get_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.get_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.get_flow] = mock_rpc
-
- request = {}
- client.get_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.get_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_get_flow_rest_required_fields(request_type=flow.GetFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_flow._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = flow.Flow()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.get_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
-
-
-def test_get_flow_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.Flow()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.get_flow(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_flow_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_flow(
- flow.GetFlowRequest(),
- name="name_value",
- )
-
-
-def test_update_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.update_flow] = mock_rpc
-
- request = {}
- client.update_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.update_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_update_flow_rest_required_fields(request_type=gcdc_flow.UpdateFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_flow._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "language_code",
- "update_mask",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "patch",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.update_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_flow._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "languageCode",
- "updateMask",
- )
- )
- & set(("flow",))
- )
-
-
-def test_update_flow_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "flow": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- flow=gcdc_flow.Flow(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_flow(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{flow.name=projects/*/locations/*/agents/*/flows/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_flow_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_flow(
- gcdc_flow.UpdateFlowRequest(),
- flow=gcdc_flow.Flow(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_train_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.train_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.train_flow] = mock_rpc
-
- request = {}
- client.train_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.train_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_train_flow_rest_required_fields(request_type=flow.TrainFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).train_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).train_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.train_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_train_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.train_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-def test_train_flow_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.train_flow(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}:train"
- % client.transport._host,
- args[1],
- )
-
-
-def test_train_flow_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.train_flow(
- flow.TrainFlowRequest(),
- name="name_value",
- )
-
-
-def test_validate_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.validate_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.validate_flow] = mock_rpc
-
- request = {}
- client.validate_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.validate_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_validate_flow_rest_required_fields(request_type=flow.ValidateFlowRequest):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).validate_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).validate_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = flow.FlowValidationResult()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = flow.FlowValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.validate_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_validate_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.validate_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-def test_get_flow_validation_result_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.get_flow_validation_result
- in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.get_flow_validation_result
- ] = mock_rpc
-
- request = {}
- client.get_flow_validation_result(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.get_flow_validation_result(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_get_flow_validation_result_rest_required_fields(
- request_type=flow.GetFlowValidationResultRequest,
-):
- transport_class = transports.FlowsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_flow_validation_result._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_flow_validation_result._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = flow.FlowValidationResult()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["flow"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "transition_routes": [
+ {
+ "name": "name_value",
+ "description": "description_value",
+ "intent": "intent_value",
+ "condition": "condition_value",
+ "trigger_fulfillment": {
+ "messages": [
+ {
+ "text": {
+ "text": ["text_value1", "text_value2"],
+ "allow_playback_interruption": True,
+ },
+ "payload": {"fields": {}},
+ "conversation_success": {"metadata": {}},
+ "output_audio_text": {
+ "text": "text_value",
+ "ssml": "ssml_value",
+ "allow_playback_interruption": True,
+ },
+ "live_agent_handoff": {"metadata": {}},
+ "end_interaction": {},
+ "play_audio": {
+ "audio_uri": "audio_uri_value",
+ "allow_playback_interruption": True,
+ },
+ "mixed_audio": {
+ "segments": [
+ {
+ "audio": b"audio_blob",
+ "uri": "uri_value",
+ "allow_playback_interruption": True,
+ }
+ ]
+ },
+ "telephony_transfer_call": {
+ "phone_number": "phone_number_value"
+ },
+ "knowledge_info_card": {},
+ "tool_call": {
+ "tool": "tool_value",
+ "action": "action_value",
+ "input_parameters": {},
+ },
+ "channel": "channel_value",
+ }
+ ],
+ "webhook": "webhook_value",
+ "return_partial_responses": True,
+ "tag": "tag_value",
+ "set_parameter_actions": [
+ {
+ "parameter": "parameter_value",
+ "value": {
+ "null_value": 0,
+ "number_value": 0.1285,
+ "string_value": "string_value_value",
+ "bool_value": True,
+ "struct_value": {},
+ "list_value": {"values": {}},
+ },
+ }
+ ],
+ "conditional_cases": [
+ {
+ "cases": [
+ {
+ "condition": "condition_value",
+ "case_content": [
+ {"message": {}, "additional_cases": {}}
+ ],
+ }
+ ]
+ }
+ ],
+ "advanced_settings": {
+ "audio_export_gcs_destination": {"uri": "uri_value"},
+ "speech_settings": {
+ "endpointer_sensitivity": 2402,
+ "no_speech_timeout": {"seconds": 751, "nanos": 543},
+ "use_timeout_based_endpointing": True,
+ "models": {},
+ },
+ "dtmf_settings": {
+ "enabled": True,
+ "max_digits": 1065,
+ "finish_digit": "finish_digit_value",
+ "interdigit_timeout_duration": {},
+ "endpointing_timeout_duration": {},
+ },
+ "logging_settings": {
+ "enable_stackdriver_logging": True,
+ "enable_interaction_logging": True,
+ },
+ },
+ "enable_generative_fallback": True,
+ },
+ "target_page": "target_page_value",
+ "target_flow": "target_flow_value",
}
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = flow.FlowValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.get_flow_validation_result(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_flow_validation_result_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_flow_validation_result._get_unset_required_fields({})
- assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
-
-
-def test_get_flow_validation_result_rest_flattened():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.FlowValidationResult()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = flow.FlowValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.get_flow_validation_result(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/validationResult}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_flow_validation_result_rest_flattened_error(transport: str = "rest"):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_flow_validation_result(
- flow.GetFlowValidationResultRequest(),
- name="name_value",
- )
-
-
-def test_import_flow_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.import_flow in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.import_flow] = mock_rpc
-
- request = {}
- client.import_flow(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.import_flow(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
+ ],
+ "event_handlers": [
+ {
+ "name": "name_value",
+ "event": "event_value",
+ "trigger_fulfillment": {},
+ "target_page": "target_page_value",
+ "target_flow": "target_flow_value",
+ }
+ ],
+ "transition_route_groups": [
+ "transition_route_groups_value1",
+ "transition_route_groups_value2",
+ ],
+ "nlu_settings": {
+ "model_type": 1,
+ "classification_threshold": 0.25520000000000004,
+ "model_training_mode": 1,
+ },
+ "advanced_settings": {},
+ "knowledge_connector_settings": {
+ "enabled": True,
+ "trigger_fulfillment": {},
+ "target_page": "target_page_value",
+ "target_flow": "target_flow_value",
+ "data_store_connections": [
+ {"data_store_type": 1, "data_store": "data_store_value"}
+ ],
+ },
+ "multi_language_settings": {
+ "enable_multi_language_detection": True,
+ "supported_response_language_codes": [
+ "supported_response_language_codes_value1",
+ "supported_response_language_codes_value2",
+ ],
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
-def test_import_flow_rest_required_fields(request_type=flow.ImportFlowRequest):
- transport_class = transports.FlowsRestTransport
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_flow.CreateFlowRequest.meta.fields["flow"]
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
- # verify fields with default values are dropped
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).import_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
- # verify required fields with default values are now present
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
- jsonified_request["parent"] = "parent_value"
+ subfields_not_in_runtime = []
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).import_flow._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["flow"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["flow"][field])):
+ del request_init["flow"][field][i][subfield]
+ else:
+ del request_init["flow"][field][subfield]
request = request_type(**request_init)
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.import_flow(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
-def test_import_flow_rest_unset_required_fields():
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_flow(request)
- unset_fields = transport.import_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("parent",)))
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_flow.Flow)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.transition_route_groups == ["transition_route_groups_value"]
-def test_export_flow_rest_use_cached_wrapped_rpc():
+def test_create_flow_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -5957,37 +5049,33 @@ def test_export_flow_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.export_flow in client._transport._wrapped_methods
+ assert client._transport.create_flow in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.export_flow] = mock_rpc
+ client._transport._wrapped_methods[client._transport.create_flow] = mock_rpc
request = {}
- client.export_flow(request)
+ client.create_flow(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.export_flow(request)
+ client.create_flow(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_export_flow_rest_required_fields(request_type=flow.ExportFlowRequest):
+def test_create_flow_rest_required_fields(request_type=gcdc_flow.CreateFlowRequest):
transport_class = transports.FlowsRestTransport
request_init = {}
- request_init["name"] = ""
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5998,21 +5086,23 @@ def test_export_flow_rest_required_fields(request_type=flow.ExportFlowRequest):
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).export_flow._get_unset_required_fields(jsonified_request)
+ ).create_flow._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
+ jsonified_request["parent"] = "parent_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).export_flow._get_unset_required_fields(jsonified_request)
+ ).create_flow._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6021,7 +5111,7 @@ def test_export_flow_rest_required_fields(request_type=flow.ExportFlowRequest):
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = gcdc_flow.Flow()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6041,940 +5131,658 @@ def test_export_flow_rest_required_fields(request_type=flow.ExportFlowRequest):
response_value = Response()
response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.export_flow(request)
+ response = client.create_flow(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_export_flow_rest_unset_required_fields():
+def test_create_flow_rest_unset_required_fields():
transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.export_flow._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.FlowsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.FlowsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = FlowsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.FlowsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = FlowsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = FlowsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ unset_fields = transport.create_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("languageCode",))
+ & set(
+ (
+ "parent",
+ "flow",
+ )
)
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.FlowsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
)
- with pytest.raises(ValueError):
- client = FlowsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.FlowsGrpcTransport(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_flow_rest_interceptors(null_interceptor):
+ transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.FlowsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.FlowsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.FlowsGrpcTransport,
- transports.FlowsGrpcAsyncIOTransport,
- transports.FlowsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = FlowsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.FlowsRestInterceptor, "post_create_flow"
+ ) as post, mock.patch.object(
+ transports.FlowsRestInterceptor, "pre_create_flow"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_flow.CreateFlowRequest.pb(gcdc_flow.CreateFlowRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_flow_empty_call_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_flow.Flow.to_json(gcdc_flow.Flow())
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_flow), "__call__") as call:
- call.return_value = gcdc_flow.Flow()
- client.create_flow(request=None)
+ request = gcdc_flow.CreateFlowRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_flow.Flow()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.CreateFlowRequest()
+ client.create_flow(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- assert args[0] == request_msg
+ pre.assert_called_once()
+ post.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_flow_empty_call_grpc():
+def test_create_flow_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_flow.CreateFlowRequest
+):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_flow), "__call__") as call:
- call.return_value = None
- client.delete_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.DeleteFlowRequest()
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_flow(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_flows_empty_call_grpc():
+def test_create_flow_rest_flattened():
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_flows), "__call__") as call:
- call.return_value = flow.ListFlowsResponse()
- client.list_flows(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ListFlowsRequest()
-
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_flow.Flow()
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_flow_empty_call_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ flow=gcdc_flow.Flow(name="name_value"),
+ )
+ mock_args.update(sample_request)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_flow), "__call__") as call:
- call.return_value = flow.Flow()
- client.get_flow(request=None)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowRequest()
+ client.create_flow(**mock_args)
- assert args[0] == request_msg
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/flows"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_flow_empty_call_grpc():
+def test_create_flow_rest_flattened_error(transport: str = "rest"):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_flow), "__call__") as call:
- call.return_value = gcdc_flow.Flow()
- client.update_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.UpdateFlowRequest()
-
- assert args[0] == request_msg
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_flow(
+ gcdc_flow.CreateFlowRequest(),
+ parent="parent_value",
+ flow=gcdc_flow.Flow(name="name_value"),
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_train_flow_empty_call_grpc():
+def test_create_flow_rest_error():
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.train_flow), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.train_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.TrainFlowRequest()
-
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_validate_flow_empty_call_grpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ flow.DeleteFlowRequest,
+ dict,
+ ],
+)
+def test_delete_flow_rest(request_type):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_flow), "__call__") as call:
- call.return_value = flow.FlowValidationResult()
- client.validate_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ValidateFlowRequest()
-
- assert args[0] == request_msg
-
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_flow_validation_result_empty_call_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_flow_validation_result), "__call__"
- ) as call:
- call.return_value = flow.FlowValidationResult()
- client.get_flow_validation_result(request=None)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowValidationResultRequest()
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_flow(request)
- assert args[0] == request_msg
+ # Establish that the response is the type that we expect.
+ assert response is None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_flow_empty_call_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+def test_delete_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_flow), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.import_flow(request=None)
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ImportFlowRequest()
+ # Ensure method has been cached
+ assert client._transport.delete_flow in client._transport._wrapped_methods
- assert args[0] == request_msg
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_flow] = mock_rpc
+ request = {}
+ client.delete_flow(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_flow_empty_call_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_flow), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_flow(request=None)
+ client.delete_flow(request)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ExportFlowRequest()
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
- assert args[0] == request_msg
+def test_delete_flow_rest_required_fields(request_type=flow.DeleteFlowRequest):
+ transport_class = transports.FlowsRestTransport
-def test_transport_kind_grpc_asyncio():
- transport = FlowsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- assert transport.kind == "grpc_asyncio"
+ # verify fields with default values are dropped
-def test_initialize_client_w_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with default values are now present
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ jsonified_request["name"] = "name_value"
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
- )
- await client.create_flow(request=None)
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_flow._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("force",))
+ jsonified_request.update(unset_fields)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.CreateFlowRequest()
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
- assert args[0] == request_msg
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "delete",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_flow(request=None)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.DeleteFlowRequest()
+ response = client.delete_flow(request)
- assert args[0] == request_msg
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_flows_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_delete_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_flows), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- flow.ListFlowsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_flows(request=None)
+ unset_fields = transport.delete_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("force",)) & set(("name",)))
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ListFlowsRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_flow_rest_interceptors(null_interceptor):
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
+ )
+ client = FlowsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.FlowsRestInterceptor, "pre_delete_flow"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = flow.DeleteFlowRequest.pb(flow.DeleteFlowRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ request = flow.DeleteFlowRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
+ client.delete_flow(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- await client.get_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowRequest()
- assert args[0] == request_msg
+ pre.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_delete_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.DeleteFlowRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
- )
- await client.update_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.UpdateFlowRequest()
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_flow(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_train_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_delete_flow_rest_flattened():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.train_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.train_flow(request=None)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.TrainFlowRequest()
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
- assert args[0] == request_msg
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_validate_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ client.delete_flow(**mock_args)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- flow.FlowValidationResult(
- name="name_value",
- )
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}"
+ % client.transport._host,
+ args[1],
)
- await client.validate_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ValidateFlowRequest()
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_flow_validation_result_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_delete_flow_rest_flattened_error(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_flow_validation_result), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- flow.FlowValidationResult(
- name="name_value",
- )
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_flow(
+ flow.DeleteFlowRequest(),
+ name="name_value",
)
- await client.get_flow_validation_result(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowValidationResultRequest()
- assert args[0] == request_msg
+def test_delete_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_import_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ flow.ListFlowsRequest,
+ dict,
+ ],
+)
+def test_list_flows_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = flow.ListFlowsResponse(
+ next_page_token="next_page_token_value",
)
- await client.import_flow(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ImportFlowRequest()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = flow.ListFlowsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- assert args[0] == request_msg
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_flows(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListFlowsPager)
+ assert response.next_page_token == "next_page_token_value"
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_flow_empty_call_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_flow), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
+def test_list_flows_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- await client.export_flow(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ExportFlowRequest()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- assert args[0] == request_msg
+ # Ensure method has been cached
+ assert client._transport.list_flows in client._transport._wrapped_methods
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_flows] = mock_rpc
-def test_transport_kind_rest():
- transport = FlowsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
+ request = {}
+ client.list_flows(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_create_flow_rest_bad_request(request_type=gcdc_flow.CreateFlowRequest):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
+ client.list_flows(request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_flow(request)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_flow.CreateFlowRequest,
- dict,
- ],
-)
-def test_create_flow_rest_call_success(request_type):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+def test_list_flows_rest_required_fields(request_type=flow.ListFlowsRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["flow"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "description": "description_value",
- "transition_routes": [
- {
- "name": "name_value",
- "description": "description_value",
- "intent": "intent_value",
- "condition": "condition_value",
- "trigger_fulfillment": {
- "messages": [
- {
- "text": {
- "text": ["text_value1", "text_value2"],
- "allow_playback_interruption": True,
- },
- "payload": {"fields": {}},
- "conversation_success": {"metadata": {}},
- "output_audio_text": {
- "text": "text_value",
- "ssml": "ssml_value",
- "allow_playback_interruption": True,
- },
- "live_agent_handoff": {"metadata": {}},
- "end_interaction": {},
- "play_audio": {
- "audio_uri": "audio_uri_value",
- "allow_playback_interruption": True,
- },
- "mixed_audio": {
- "segments": [
- {
- "audio": b"audio_blob",
- "uri": "uri_value",
- "allow_playback_interruption": True,
- }
- ]
- },
- "telephony_transfer_call": {
- "phone_number": "phone_number_value"
- },
- "knowledge_info_card": {},
- "tool_call": {
- "tool": "tool_value",
- "action": "action_value",
- "input_parameters": {},
- },
- "channel": "channel_value",
- }
- ],
- "webhook": "webhook_value",
- "return_partial_responses": True,
- "tag": "tag_value",
- "set_parameter_actions": [
- {
- "parameter": "parameter_value",
- "value": {
- "null_value": 0,
- "number_value": 0.1285,
- "string_value": "string_value_value",
- "bool_value": True,
- "struct_value": {},
- "list_value": {"values": {}},
- },
- }
- ],
- "conditional_cases": [
- {
- "cases": [
- {
- "condition": "condition_value",
- "case_content": [
- {"message": {}, "additional_cases": {}}
- ],
- }
- ]
- }
- ],
- "advanced_settings": {
- "audio_export_gcs_destination": {"uri": "uri_value"},
- "speech_settings": {
- "endpointer_sensitivity": 2402,
- "no_speech_timeout": {"seconds": 751, "nanos": 543},
- "use_timeout_based_endpointing": True,
- "models": {},
- },
- "dtmf_settings": {
- "enabled": True,
- "max_digits": 1065,
- "finish_digit": "finish_digit_value",
- "interdigit_timeout_duration": {},
- "endpointing_timeout_duration": {},
- },
- "logging_settings": {
- "enable_stackdriver_logging": True,
- "enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
- },
- },
- "enable_generative_fallback": True,
- },
- "target_page": "target_page_value",
- "target_flow": "target_flow_value",
- }
- ],
- "event_handlers": [
- {
- "name": "name_value",
- "event": "event_value",
- "trigger_fulfillment": {},
- "target_page": "target_page_value",
- "target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
- }
- ],
- "transition_route_groups": [
- "transition_route_groups_value1",
- "transition_route_groups_value2",
- ],
- "nlu_settings": {
- "model_type": 1,
- "classification_threshold": 0.25520000000000004,
- "model_training_mode": 1,
- },
- "advanced_settings": {},
- "knowledge_connector_settings": {
- "enabled": True,
- "trigger_fulfillment": {},
- "target_page": "target_page_value",
- "target_flow": "target_flow_value",
- "data_store_connections": [
- {"data_store_type": 1, "data_store": "data_store_value"}
- ],
- },
- "multi_language_settings": {
- "enable_multi_language_detection": True,
- "supported_response_language_codes": [
- "supported_response_language_codes_value1",
- "supported_response_language_codes_value2",
- ],
- },
- "locked": True,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
+ # verify fields with default values are dropped
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_flow.CreateFlowRequest.meta.fields["flow"]
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_flows._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
+ # verify required fields with default values are now present
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+ jsonified_request["parent"] = "parent_value"
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_flows._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "language_code",
+ "page_size",
+ "page_token",
+ )
+ )
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
- subfields_not_in_runtime = []
+ # Designate an appropriate value for the returned response.
+ return_value = flow.ListFlowsResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["flow"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
+ response_value = Response()
+ response_value.status_code = 200
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
+ # Convert return value to protobuf type
+ return_value = flow.ListFlowsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["flow"][field])):
- del request_init["flow"][field][i][subfield]
- else:
- del request_init["flow"][field][subfield]
- request = request_type(**request_init)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
+ response = client.list_flows(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_flow(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_flow.Flow)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+def test_list_flows_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.list_flows._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "languageCode",
+ "pageSize",
+ "pageToken",
+ )
+ )
+ & set(("parent",))
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_flow_rest_interceptors(null_interceptor):
+def test_list_flows_rest_interceptors(null_interceptor):
transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- transports.FlowsRestInterceptor, "post_create_flow"
+ transports.FlowsRestInterceptor, "post_list_flows"
) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_create_flow"
+ transports.FlowsRestInterceptor, "pre_list_flows"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = gcdc_flow.CreateFlowRequest.pb(gcdc_flow.CreateFlowRequest())
+ pb_message = flow.ListFlowsRequest.pb(flow.ListFlowsRequest())
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -6982,20 +5790,22 @@ def test_create_flow_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_flow.Flow.to_json(gcdc_flow.Flow())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = flow.ListFlowsResponse.to_json(
+ flow.ListFlowsResponse()
+ )
- request = gcdc_flow.CreateFlowRequest()
+ request = flow.ListFlowsRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = gcdc_flow.Flow()
+ post.return_value = flow.ListFlowsResponse()
- client.create_flow(
+ client.list_flows(
request,
metadata=[
("key", "val"),
@@ -7007,14 +5817,16 @@ def test_create_flow_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_delete_flow_rest_bad_request(request_type=flow.DeleteFlowRequest):
+def test_list_flows_rest_bad_request(
+ transport: str = "rest", request_type=flow.ListFlowsRequest
+):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -7022,25 +5834,142 @@ def test_delete_flow_rest_bad_request(request_type=flow.DeleteFlowRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.delete_flow(request)
+ client.list_flows(request)
+
+
+def test_list_flows_rest_flattened():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = flow.ListFlowsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = flow.ListFlowsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.list_flows(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/flows"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_flows_rest_flattened_error(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_flows(
+ flow.ListFlowsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_flows_rest_pager(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # TODO(kbandes): remove this mock unless there's a good reason for it.
+ # with mock.patch.object(path_template, 'transcode') as transcode:
+ # Set the response as a series of pages
+ response = (
+ flow.ListFlowsResponse(
+ flows=[
+ flow.Flow(),
+ flow.Flow(),
+ flow.Flow(),
+ ],
+ next_page_token="abc",
+ ),
+ flow.ListFlowsResponse(
+ flows=[],
+ next_page_token="def",
+ ),
+ flow.ListFlowsResponse(
+ flows=[
+ flow.Flow(),
+ ],
+ next_page_token="ghi",
+ ),
+ flow.ListFlowsResponse(
+ flows=[
+ flow.Flow(),
+ flow.Flow(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(flow.ListFlowsResponse.to_json(x) for x in response)
+ return_values = tuple(Response() for i in response)
+ for return_val, response_val in zip(return_values, response):
+ return_val._content = response_val.encode("UTF-8")
+ return_val.status_code = 200
+ req.side_effect = return_values
+
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+
+ pager = client.list_flows(request=sample_request)
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, flow.Flow) for i in results)
+
+ pages = list(client.list_flows(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
@pytest.mark.parametrize(
"request_type",
[
- flow.DeleteFlowRequest,
+ flow.GetFlowRequest,
dict,
],
)
-def test_delete_flow_rest_call_success(request_type):
+def test_get_flow_rest(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -7052,249 +5981,149 @@ def test_delete_flow_rest_call_success(request_type):
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_flow(request)
+ response = client.get_flow(request)
# Establish that the response is the type that we expect.
- assert response is None
-
+ assert isinstance(response, flow.Flow)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.transition_route_groups == ["transition_route_groups_value"]
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_flow_rest_interceptors(null_interceptor):
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
- )
- client = FlowsClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_delete_flow"
- ) as pre:
- pre.assert_not_called()
- pb_message = flow.DeleteFlowRequest.pb(flow.DeleteFlowRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+def test_get_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = flow.DeleteFlowRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
+ # Ensure method has been cached
+ assert client._transport.get_flow in client._transport._wrapped_methods
- client.delete_flow(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[client._transport.get_flow] = mock_rpc
- pre.assert_called_once()
+ request = {}
+ client.get_flow(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_flows_rest_bad_request(request_type=flow.ListFlowsRequest):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
+ client.get_flow(request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_flows(request)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-@pytest.mark.parametrize(
- "request_type",
- [
- flow.ListFlowsRequest,
- dict,
- ],
-)
-def test_list_flows_rest_call_success(request_type):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+def test_get_flow_rest_required_fields(request_type=flow.GetFlowRequest):
+ transport_class = transports.FlowsRestTransport
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {}
+ request_init["name"] = ""
request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.ListFlowsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = flow.ListFlowsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_flows(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListFlowsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_flows_rest_interceptors(null_interceptor):
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- client = FlowsClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.FlowsRestInterceptor, "post_list_flows"
- ) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_list_flows"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = flow.ListFlowsRequest.pb(flow.ListFlowsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+ # verify fields with default values are dropped
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = flow.ListFlowsResponse.to_json(flow.ListFlowsResponse())
- req.return_value.content = return_value
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
- request = flow.ListFlowsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = flow.ListFlowsResponse()
+ # verify required fields with default values are now present
- client.list_flows(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
+ jsonified_request["name"] = "name_value"
- pre.assert_called_once()
- post.assert_called_once()
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_flow._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
+ jsonified_request.update(unset_fields)
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-def test_get_flow_rest_bad_request(request_type=flow.GetFlowRequest):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
request = request_type(**request_init)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_flow(request)
+ # Designate an appropriate value for the returned response.
+ return_value = flow.Flow()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+ response_value = Response()
+ response_value.status_code = 200
-@pytest.mark.parametrize(
- "request_type",
- [
- flow.GetFlowRequest,
- dict,
- ],
-)
-def test_get_flow_rest_call_success(request_type):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+ # Convert return value to protobuf type
+ return_value = flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
+ response = client.get_flow(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_flow(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, flow.Flow)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+def test_get_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.get_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -7304,7 +6133,6 @@ def test_get_flow_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -7324,10 +6152,10 @@ def test_get_flow_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = flow.Flow.to_json(flow.Flow())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = flow.Flow.to_json(flow.Flow())
request = flow.GetFlowRequest()
metadata = [
@@ -7349,15 +6177,17 @@ def test_get_flow_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_update_flow_rest_bad_request(request_type=gcdc_flow.UpdateFlowRequest):
+def test_get_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.GetFlowRequest
+):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "flow": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
}
request = request_type(**request_init)
@@ -7366,13 +6196,76 @@ def test_update_flow_rest_bad_request(request_type=gcdc_flow.UpdateFlowRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.update_flow(request)
+ client.get_flow(request)
+
+
+def test_get_flow_rest_flattened():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = flow.Flow()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.get_flow(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_flow_rest_flattened_error(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_flow(
+ flow.GetFlowRequest(),
+ name="name_value",
+ )
+
+
+def test_get_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -7382,9 +6275,10 @@ def test_update_flow_rest_bad_request(request_type=gcdc_flow.UpdateFlowRequest):
dict,
],
)
-def test_update_flow_rest_call_success(request_type):
+def test_update_flow_rest(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -7490,7 +6384,6 @@ def test_update_flow_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -7506,7 +6399,6 @@ def test_update_flow_rest_call_success(request_type):
"trigger_fulfillment": {},
"target_page": "target_page_value",
"target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
}
],
"transition_route_groups": [
@@ -7535,7 +6427,6 @@ def test_update_flow_rest_call_success(request_type):
"supported_response_language_codes_value2",
],
},
- "locked": True,
}
# The version of a generated dependency at test runtime may differ from the version used during generation.
# Delete any fields which are not present in the current runtime dependency
@@ -7606,35 +6497,161 @@ def get_message_fields(field):
del request_init["flow"][field][subfield]
request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_flow.Flow(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- locked=True,
- )
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_flow.Flow(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_flow(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_flow.Flow)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.transition_route_groups == ["transition_route_groups_value"]
+
+
+def test_update_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_flow in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_flow] = mock_rpc
+
+ request = {}
+ client.update_flow(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_flow_rest_required_fields(request_type=gcdc_flow.UpdateFlowRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_flow._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "language_code",
+ "update_mask",
+ )
+ )
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_flow.Flow()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "patch",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.update_flow(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = gcdc_flow.Flow.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_flow(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_flow.Flow)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.transition_route_groups == ["transition_route_groups_value"]
- assert response.locked is True
+def test_update_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.update_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "languageCode",
+ "updateMask",
+ )
+ )
+ & set(("flow",))
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -7644,7 +6661,6 @@ def test_update_flow_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -7664,10 +6680,10 @@ def test_update_flow_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_flow.Flow.to_json(gcdc_flow.Flow())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_flow.Flow.to_json(gcdc_flow.Flow())
request = gcdc_flow.UpdateFlowRequest()
metadata = [
@@ -7689,13 +6705,19 @@ def test_update_flow_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_train_flow_rest_bad_request(request_type=flow.TrainFlowRequest):
+def test_update_flow_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_flow.UpdateFlowRequest
+):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ "flow": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
}
request = request_type(**request_init)
@@ -7704,13 +6726,80 @@ def test_train_flow_rest_bad_request(request_type=flow.TrainFlowRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.train_flow(request)
+ client.update_flow(request)
+
+
+def test_update_flow_rest_flattened():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_flow.Flow()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "flow": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ flow=gcdc_flow.Flow(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_flow.Flow.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.update_flow(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{flow.name=projects/*/locations/*/agents/*/flows/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_flow_rest_flattened_error(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_flow(
+ gcdc_flow.UpdateFlowRequest(),
+ flow=gcdc_flow.Flow(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_update_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -7720,32 +6809,153 @@ def test_train_flow_rest_bad_request(request_type=flow.TrainFlowRequest):
dict,
],
)
-def test_train_flow_rest_call_success(request_type):
+def test_train_flow_rest(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.train_flow(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_train_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.train_flow in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.train_flow] = mock_rpc
+
+ request = {}
+ client.train_flow(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.train_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_train_flow_rest_required_fields(request_type=flow.TrainFlowRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).train_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).train_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
+
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.train_flow(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.train_flow(request)
+def test_train_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ unset_fields = transport.train_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -7755,7 +6965,6 @@ def test_train_flow_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -7777,10 +6986,12 @@ def test_train_flow_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
request = flow.TrainFlowRequest()
metadata = [
@@ -7802,10 +7013,14 @@ def test_train_flow_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_validate_flow_rest_bad_request(request_type=flow.ValidateFlowRequest):
+def test_train_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.TrainFlowRequest
+):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
"name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
@@ -7817,13 +7032,74 @@ def test_validate_flow_rest_bad_request(request_type=flow.ValidateFlowRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.validate_flow(request)
+ client.train_flow(request)
+
+
+def test_train_flow_rest_flattened():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.train_flow(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*}:train"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_train_flow_rest_flattened_error(transport: str = "rest"):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.train_flow(
+ flow.TrainFlowRequest(),
+ name="name_value",
+ )
+
+
+def test_train_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -7833,9 +7109,10 @@ def test_validate_flow_rest_bad_request(request_type=flow.ValidateFlowRequest):
dict,
],
)
-def test_validate_flow_rest_call_success(request_type):
+def test_validate_flow_rest(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -7852,13 +7129,13 @@ def test_validate_flow_rest_call_success(request_type):
)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = flow.FlowValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.validate_flow(request)
@@ -7867,147 +7144,143 @@ def test_validate_flow_rest_call_success(request_type):
assert response.name == "name_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_validate_flow_rest_interceptors(null_interceptor):
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
- )
- client = FlowsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.FlowsRestInterceptor, "post_validate_flow"
- ) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_validate_flow"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = flow.ValidateFlowRequest.pb(flow.ValidateFlowRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+def test_validate_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = flow.FlowValidationResult.to_json(flow.FlowValidationResult())
- req.return_value.content = return_value
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = flow.ValidateFlowRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = flow.FlowValidationResult()
+ # Ensure method has been cached
+ assert client._transport.validate_flow in client._transport._wrapped_methods
- client.validate_flow(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[client._transport.validate_flow] = mock_rpc
- pre.assert_called_once()
- post.assert_called_once()
+ request = {}
+ client.validate_flow(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_get_flow_validation_result_rest_bad_request(
- request_type=flow.GetFlowValidationResultRequest,
-):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
- }
+ client.validate_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_validate_flow_rest_required_fields(request_type=flow.ValidateFlowRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_flow_validation_result(request)
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).validate_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).validate_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- flow.GetFlowValidationResultRequest,
- dict,
- ],
-)
-def test_get_flow_validation_result_rest_call_success(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = flow.FlowValidationResult()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
- }
- request = request_type(**request_init)
+ # Convert return value to protobuf type
+ return_value = flow.FlowValidationResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = flow.FlowValidationResult(
- name="name_value",
- )
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ response = client.validate_flow(request)
- # Convert return value to protobuf type
- return_value = flow.FlowValidationResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_flow_validation_result(request)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Establish that the response is the type that we expect.
- assert isinstance(response, flow.FlowValidationResult)
- assert response.name == "name_value"
+
+def test_validate_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.validate_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_flow_validation_result_rest_interceptors(null_interceptor):
+def test_validate_flow_rest_interceptors(null_interceptor):
transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- transports.FlowsRestInterceptor, "post_get_flow_validation_result"
+ transports.FlowsRestInterceptor, "post_validate_flow"
) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_get_flow_validation_result"
+ transports.FlowsRestInterceptor, "pre_validate_flow"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = flow.GetFlowValidationResultRequest.pb(
- flow.GetFlowValidationResultRequest()
- )
+ pb_message = flow.ValidateFlowRequest.pb(flow.ValidateFlowRequest())
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -8015,12 +7288,14 @@ def test_get_flow_validation_result_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = flow.FlowValidationResult.to_json(flow.FlowValidationResult())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = flow.FlowValidationResult.to_json(
+ flow.FlowValidationResult()
+ )
- request = flow.GetFlowValidationResultRequest()
+ request = flow.ValidateFlowRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
@@ -8028,7 +7303,7 @@ def test_get_flow_validation_result_rest_interceptors(null_interceptor):
pre.return_value = request, metadata
post.return_value = flow.FlowValidationResult()
- client.get_flow_validation_result(
+ client.validate_flow(
request,
metadata=[
("key", "val"),
@@ -8040,12 +7315,18 @@ def test_get_flow_validation_result_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_import_flow_rest_bad_request(request_type=flow.ImportFlowRequest):
+def test_validate_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.ValidateFlowRequest
+):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -8053,183 +7334,208 @@ def test_import_flow_rest_bad_request(request_type=flow.ImportFlowRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.import_flow(request)
+ client.validate_flow(request)
+
+
+def test_validate_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- flow.ImportFlowRequest,
+ flow.GetFlowValidationResultRequest,
dict,
],
)
-def test_import_flow_rest_call_success(request_type):
+def test_get_flow_validation_result_rest(request_type):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = flow.FlowValidationResult(
+ name="name_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = flow.FlowValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.import_flow(request)
+ response = client.get_flow_validation_result(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert isinstance(response, flow.FlowValidationResult)
+ assert response.name == "name_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_import_flow_rest_interceptors(null_interceptor):
- transport = transports.FlowsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
+def test_get_flow_validation_result_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.get_flow_validation_result
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.get_flow_validation_result
+ ] = mock_rpc
+
+ request = {}
+ client.get_flow_validation_result(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_flow_validation_result(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_get_flow_validation_result_rest_required_fields(
+ request_type=flow.GetFlowValidationResultRequest,
+):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- client = FlowsClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.FlowsRestInterceptor, "post_import_flow"
- ) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_import_flow"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = flow.ImportFlowRequest.pb(flow.ImportFlowRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+ # verify fields with default values are dropped
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_flow_validation_result._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
- request = flow.ImportFlowRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ # verify required fields with default values are now present
- client.import_flow(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
+ jsonified_request["name"] = "name_value"
- pre.assert_called_once()
- post.assert_called_once()
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_flow_validation_result._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
+ jsonified_request.update(unset_fields)
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-def test_export_flow_rest_bad_request(request_type=flow.ExportFlowRequest):
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
request = request_type(**request_init)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_flow(request)
+ # Designate an appropriate value for the returned response.
+ return_value = flow.FlowValidationResult()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+ response_value = Response()
+ response_value.status_code = 200
-@pytest.mark.parametrize(
- "request_type",
- [
- flow.ExportFlowRequest,
- dict,
- ],
-)
-def test_export_flow_rest_call_success(request_type):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+ # Convert return value to protobuf type
+ return_value = flow.FlowValidationResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
+ response = client.get_flow_validation_result(request)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_flow(request)
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+def test_get_flow_validation_result_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.get_flow_validation_result._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_flow_rest_interceptors(null_interceptor):
+def test_get_flow_validation_result_rest_interceptors(null_interceptor):
transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
client = FlowsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.FlowsRestInterceptor, "post_export_flow"
+ transports.FlowsRestInterceptor, "post_get_flow_validation_result"
) as post, mock.patch.object(
- transports.FlowsRestInterceptor, "pre_export_flow"
+ transports.FlowsRestInterceptor, "pre_get_flow_validation_result"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = flow.ExportFlowRequest.pb(flow.ExportFlowRequest())
+ pb_message = flow.GetFlowValidationResultRequest.pb(
+ flow.GetFlowValidationResultRequest()
+ )
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -8237,20 +7543,22 @@ def test_export_flow_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = flow.FlowValidationResult.to_json(
+ flow.FlowValidationResult()
+ )
- request = flow.ExportFlowRequest()
+ request = flow.GetFlowValidationResultRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ post.return_value = flow.FlowValidationResult()
- client.export_flow(
+ client.get_flow_validation_result(
request,
metadata=[
("key", "val"),
@@ -8262,251 +7570,317 @@ def test_export_flow_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_get_flow_validation_result_rest_bad_request(
+ transport: str = "rest", request_type=flow.GetFlowValidationResultRequest
+):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
+ }
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_location(request)
+ client.get_flow_validation_result(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
+def test_get_flow_validation_result_rest_flattened():
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = flow.FlowValidationResult()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/validationResult"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = flow.FlowValidationResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_location(request)
+ client.get_flow_validation_result(**mock_args)
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/validationResult}"
+ % client.transport._host,
+ args[1],
+ )
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
+def test_get_flow_validation_result_rest_flattened_error(transport: str = "rest"):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_flow_validation_result(
+ flow.GetFlowValidationResultRequest(),
+ name="name_value",
+ )
+
+
+def test_get_flow_validation_result_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.ListLocationsRequest,
+ flow.ImportFlowRequest,
dict,
],
)
-def test_list_locations_rest(request_type):
+def test_import_flow_rest(request_type):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.list_locations(request)
+ response = client.import_flow(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ assert response.operation.name == "operations/spam"
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_import_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.import_flow in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.import_flow] = mock_rpc
+
+ request = {}
+ client.import_flow(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.import_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_import_flow_rest_required_fields(request_type=flow.ImportFlowRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).import_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).import_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1/operations/sample2"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- req.return_value = response_value
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- response = client.cancel_operation(request)
+ response = client.import_flow(request)
- # Establish that the response is the type that we expect.
- assert response is None
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_import_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
+ unset_fields = transport.import_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("parent",)))
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = FlowsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_import_flow_rest_interceptors(null_interceptor):
+ transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
+ client = FlowsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.FlowsRestInterceptor, "post_import_flow"
+ ) as post, mock.patch.object(
+ transports.FlowsRestInterceptor, "pre_import_flow"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = flow.ImportFlowRequest.pb(flow.ImportFlowRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- req.return_value = response_value
+ request = flow.ImportFlowRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- response = client.get_operation(request)
+ client.import_flow(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_import_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.ImportFlowRequest
):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -8514,272 +7888,365 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
+ client.import_flow(request)
+
+
+def test_import_flow_rest_error():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- operations_pb2.ListOperationsRequest,
+ flow.ExportFlowRequest,
dict,
],
)
-def test_list_operations_rest(request_type):
+def test_export_flow_rest(request_type):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.list_operations(request)
+ response = client.export_flow(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ assert response.operation.name == "operations/spam"
-def test_initialize_client_w_rest():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
+def test_export_flow_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_flow_empty_call_rest():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Ensure method has been cached
+ assert client._transport.export_flow in client._transport._wrapped_methods
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_flow), "__call__") as call:
- client.create_flow(request=None)
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.export_flow] = mock_rpc
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.CreateFlowRequest()
+ request = {}
+ client.export_flow(request)
- assert args[0] == request_msg
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_flow_empty_call_rest():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ client.export_flow(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_export_flow_rest_required_fields(request_type=flow.ExportFlowRequest):
+ transport_class = transports.FlowsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_flow), "__call__") as call:
- client.delete_flow(request=None)
+ # verify fields with default values are dropped
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.DeleteFlowRequest()
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).export_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
- assert args[0] == request_msg
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).export_flow._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_flows_empty_call_rest():
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
+ request = request_type(**request_init)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_flows), "__call__") as call:
- client.list_flows(request=None)
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ListFlowsRequest()
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- assert args[0] == request_msg
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.export_flow(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_flow_empty_call_rest():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_flow), "__call__") as call:
- client.get_flow(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowRequest()
+def test_export_flow_rest_unset_required_fields():
+ transport = transports.FlowsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
- assert args[0] == request_msg
+ unset_fields = transport.export_flow._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_flow_empty_call_rest():
- client = FlowsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_flow_rest_interceptors(null_interceptor):
+ transport = transports.FlowsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.FlowsRestInterceptor(),
)
+ client = FlowsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.FlowsRestInterceptor, "post_export_flow"
+ ) as post, mock.patch.object(
+ transports.FlowsRestInterceptor, "pre_export_flow"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = flow.ExportFlowRequest.pb(flow.ExportFlowRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_flow), "__call__") as call:
- client.update_flow(request=None)
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_flow.UpdateFlowRequest()
+ request = flow.ExportFlowRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- assert args[0] == request_msg
+ client.export_flow(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_train_flow_empty_call_rest():
+def test_export_flow_rest_bad_request(
+ transport: str = "rest", request_type=flow.ExportFlowRequest
+):
client = FlowsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.train_flow), "__call__") as call:
- client.train_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.TrainFlowRequest()
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.export_flow(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_validate_flow_empty_call_rest():
+def test_export_flow_rest_error():
client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.validate_flow), "__call__") as call:
- client.validate_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ValidateFlowRequest()
-
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_flow_validation_result_empty_call_rest():
- client = FlowsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.FlowsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_flow_validation_result), "__call__"
- ) as call:
- client.get_flow_validation_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.GetFlowValidationResultRequest()
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.FlowsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = FlowsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- assert args[0] == request_msg
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.FlowsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = FlowsClient(
+ client_options=options,
+ transport=transport,
+ )
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = FlowsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_flow_empty_call_rest():
- client = FlowsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.FlowsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = FlowsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_flow), "__call__") as call:
- client.import_flow(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ImportFlowRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.FlowsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = FlowsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_flow_empty_call_rest():
- client = FlowsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.FlowsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_flow), "__call__") as call:
- client.export_flow(request=None)
+ transport = transports.FlowsGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = flow.ExportFlowRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.FlowsGrpcTransport,
+ transports.FlowsGrpcAsyncIOTransport,
+ transports.FlowsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_flows_rest_lro_client():
- client = FlowsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = FlowsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -9039,6 +8506,23 @@ def test_flows_http_transport_client_cert_source_for_mtls():
mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_flows_rest_lro_client():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
@pytest.mark.parametrize(
"transport_name",
[
@@ -9407,40 +8891,11 @@ def test_parse_page_path():
assert expected == actual
-def test_playbook_path():
- project = "scallop"
- location = "abalone"
- agent = "squid"
- playbook = "clam"
- expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
- project=project,
- location=location,
- agent=agent,
- playbook=playbook,
- )
- actual = FlowsClient.playbook_path(project, location, agent, playbook)
- assert expected == actual
-
-
-def test_parse_playbook_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- "agent": "oyster",
- "playbook": "nudibranch",
- }
- path = FlowsClient.playbook_path(**expected)
-
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_playbook_path(path)
- assert expected == actual
-
-
def test_tool_path():
- project = "cuttlefish"
- location = "mussel"
- agent = "winkle"
- tool = "nautilus"
+ project = "scallop"
+ location = "abalone"
+ agent = "squid"
+ tool = "clam"
expected = (
"projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format(
project=project,
@@ -9455,10 +8910,10 @@ def test_tool_path():
def test_parse_tool_path():
expected = {
- "project": "scallop",
- "location": "abalone",
- "agent": "squid",
- "tool": "clam",
+ "project": "whelk",
+ "location": "octopus",
+ "agent": "oyster",
+ "tool": "nudibranch",
}
path = FlowsClient.tool_path(**expected)
@@ -9468,11 +8923,11 @@ def test_parse_tool_path():
def test_transition_route_group_path():
- project = "whelk"
- location = "octopus"
- agent = "oyster"
- flow = "nudibranch"
- transition_route_group = "cuttlefish"
+ project = "cuttlefish"
+ location = "mussel"
+ agent = "winkle"
+ flow = "nautilus"
+ transition_route_group = "scallop"
expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
project=project,
location=location,
@@ -9488,11 +8943,11 @@ def test_transition_route_group_path():
def test_parse_transition_route_group_path():
expected = {
- "project": "mussel",
- "location": "winkle",
- "agent": "nautilus",
- "flow": "scallop",
- "transition_route_group": "abalone",
+ "project": "abalone",
+ "location": "squid",
+ "agent": "clam",
+ "flow": "whelk",
+ "transition_route_group": "octopus",
}
path = FlowsClient.transition_route_group_path(**expected)
@@ -9502,10 +8957,10 @@ def test_parse_transition_route_group_path():
def test_webhook_path():
- project = "squid"
- location = "clam"
- agent = "whelk"
- webhook = "octopus"
+ project = "oyster"
+ location = "nudibranch"
+ agent = "cuttlefish"
+ webhook = "mussel"
expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
project=project,
location=location,
@@ -9518,10 +8973,10 @@ def test_webhook_path():
def test_parse_webhook_path():
expected = {
- "project": "oyster",
- "location": "nudibranch",
- "agent": "cuttlefish",
- "webhook": "mussel",
+ "project": "winkle",
+ "location": "nautilus",
+ "agent": "scallop",
+ "webhook": "abalone",
}
path = FlowsClient.webhook_path(**expected)
@@ -9531,7 +8986,7 @@ def test_parse_webhook_path():
def test_common_billing_account_path():
- billing_account = "winkle"
+ billing_account = "squid"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -9539,117 +8994,417 @@ def test_common_billing_account_path():
assert expected == actual
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "nautilus",
- }
- path = FlowsClient.common_billing_account_path(**expected)
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = FlowsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FlowsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = FlowsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = FlowsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FlowsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = FlowsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = FlowsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FlowsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = FlowsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = FlowsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FlowsClient.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 = FlowsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = FlowsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FlowsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep:
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep:
+ transport_class = FlowsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = FlowsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = FlowsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = FlowsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = FlowsClient.common_organization_path(organization)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = FlowsClient.common_organization_path(**expected)
-
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = FlowsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = FlowsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = FlowsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = FlowsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = FlowsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep:
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep:
- transport_class = FlowsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -9679,7 +9434,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9732,7 +9487,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9777,7 +9532,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -9818,7 +9573,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9873,7 +9628,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9920,7 +9675,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -9963,7 +9718,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10018,7 +9773,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10065,7 +9820,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -10108,7 +9863,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10163,7 +9918,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10210,7 +9965,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10253,7 +10008,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10305,7 +10060,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = FlowsAsyncClient(credentials=async_anonymous_credentials())
+ client = FlowsAsyncClient(credentials=ga_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.
@@ -10351,7 +10106,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10367,41 +10122,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = FlowsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = FlowsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = FlowsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_generators.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_generators.py
index 55b832dc7a3e..347d787f286c 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_generators.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_generators.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,6 +36,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.generators import (
GeneratorsAsyncClient,
@@ -66,24 +56,10 @@
from google.cloud.dialogflowcx_v3beta1.types import generator as gcdc_generator
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1143,6 +1119,25 @@ def test_list_generators(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_generators_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 = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_generators), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_generators()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.ListGeneratorsRequest()
+
+
def test_list_generators_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1210,6 +1205,29 @@ def test_list_generators_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_generators_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_generators), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ generator.ListGeneratorsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_generators()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.ListGeneratorsRequest()
+
+
@pytest.mark.asyncio
async def test_list_generators_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1218,7 +1236,7 @@ async def test_list_generators_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1233,23 +1251,27 @@ async def test_list_generators_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_generators
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_generators(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_generators(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1257,7 +1279,7 @@ async def test_list_generators_async(
transport: str = "grpc_asyncio", request_type=generator.ListGeneratorsRequest
):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1323,7 +1345,7 @@ def test_list_generators_field_headers():
@pytest.mark.asyncio
async def test_list_generators_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1393,7 +1415,7 @@ def test_list_generators_flattened_error():
@pytest.mark.asyncio
async def test_list_generators_flattened_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1422,7 +1444,7 @@ async def test_list_generators_flattened_async():
@pytest.mark.asyncio
async def test_list_generators_flattened_error_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1472,16 +1494,12 @@ def test_list_generators_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_generators(request={}, retry=retry, timeout=timeout)
+ pager = client.list_generators(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1532,7 +1550,7 @@ def test_list_generators_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_generators_async_pager():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1582,7 +1600,7 @@ async def test_list_generators_async_pager():
@pytest.mark.asyncio
async def test_list_generators_async_pages():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1666,6 +1684,25 @@ def test_get_generator(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_get_generator_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 = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_generator), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.GetGeneratorRequest()
+
+
def test_get_generator_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1731,6 +1768,30 @@ def test_get_generator_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_generator_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_generator), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.get_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.GetGeneratorRequest()
+
+
@pytest.mark.asyncio
async def test_get_generator_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1739,7 +1800,7 @@ async def test_get_generator_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1754,23 +1815,27 @@ async def test_get_generator_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_generator
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_generator(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_generator(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1778,7 +1843,7 @@ async def test_get_generator_async(
transport: str = "grpc_asyncio", request_type=generator.GetGeneratorRequest
):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1846,7 +1911,7 @@ def test_get_generator_field_headers():
@pytest.mark.asyncio
async def test_get_generator_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1914,7 +1979,7 @@ def test_get_generator_flattened_error():
@pytest.mark.asyncio
async def test_get_generator_flattened_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1941,7 +2006,7 @@ async def test_get_generator_flattened_async():
@pytest.mark.asyncio
async def test_get_generator_flattened_error_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1991,6 +2056,25 @@ def test_create_generator(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_create_generator_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 = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_generator), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_generator.CreateGeneratorRequest()
+
+
def test_create_generator_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2058,6 +2142,30 @@ def test_create_generator_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_generator_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_generator), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.create_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_generator.CreateGeneratorRequest()
+
+
@pytest.mark.asyncio
async def test_create_generator_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2066,7 +2174,7 @@ async def test_create_generator_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2081,23 +2189,27 @@ async def test_create_generator_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_generator
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_generator(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_generator(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2105,7 +2217,7 @@ async def test_create_generator_async(
transport: str = "grpc_asyncio", request_type=gcdc_generator.CreateGeneratorRequest
):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2173,7 +2285,7 @@ def test_create_generator_field_headers():
@pytest.mark.asyncio
async def test_create_generator_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2248,7 +2360,7 @@ def test_create_generator_flattened_error():
@pytest.mark.asyncio
async def test_create_generator_flattened_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2281,7 +2393,7 @@ async def test_create_generator_flattened_async():
@pytest.mark.asyncio
async def test_create_generator_flattened_error_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2332,6 +2444,25 @@ def test_update_generator(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_update_generator_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 = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_generator), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_generator.UpdateGeneratorRequest()
+
+
def test_update_generator_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2397,6 +2528,30 @@ def test_update_generator_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_generator_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_generator), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.update_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_generator.UpdateGeneratorRequest()
+
+
@pytest.mark.asyncio
async def test_update_generator_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2405,7 +2560,7 @@ async def test_update_generator_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2420,23 +2575,27 @@ async def test_update_generator_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_generator
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_generator(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_generator(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2444,7 +2603,7 @@ async def test_update_generator_async(
transport: str = "grpc_asyncio", request_type=gcdc_generator.UpdateGeneratorRequest
):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2512,7 +2671,7 @@ def test_update_generator_field_headers():
@pytest.mark.asyncio
async def test_update_generator_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2587,7 +2746,7 @@ def test_update_generator_flattened_error():
@pytest.mark.asyncio
async def test_update_generator_flattened_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2620,7 +2779,7 @@ async def test_update_generator_flattened_async():
@pytest.mark.asyncio
async def test_update_generator_flattened_error_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2666,6 +2825,25 @@ def test_delete_generator(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_generator_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 = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_generator), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.DeleteGeneratorRequest()
+
+
def test_delete_generator_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2731,6 +2909,25 @@ def test_delete_generator_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_generator_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_generator), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_generator()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == generator.DeleteGeneratorRequest()
+
+
@pytest.mark.asyncio
async def test_delete_generator_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2739,7 +2936,7 @@ async def test_delete_generator_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2754,23 +2951,27 @@ async def test_delete_generator_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_generator
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_generator(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_generator(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2778,7 +2979,7 @@ async def test_delete_generator_async(
transport: str = "grpc_asyncio", request_type=generator.DeleteGeneratorRequest
):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2839,7 +3040,7 @@ def test_delete_generator_field_headers():
@pytest.mark.asyncio
async def test_delete_generator_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2907,7 +3108,7 @@ def test_delete_generator_flattened_error():
@pytest.mark.asyncio
async def test_delete_generator_flattened_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2934,7 +3135,7 @@ async def test_delete_generator_flattened_async():
@pytest.mark.asyncio
async def test_delete_generator_flattened_error_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2946,18 +3147,58 @@ async def test_delete_generator_flattened_error_async():
)
-def test_list_generators_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ generator.ListGeneratorsRequest,
+ dict,
+ ],
+)
+def test_list_generators_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = generator.ListGeneratorsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = generator.ListGeneratorsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_generators(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListGeneratorsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_generators_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
# Ensure method has been cached
assert client._transport.list_generators in client._transport._wrapped_methods
@@ -3082,6 +3323,87 @@ def test_list_generators_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_generators_rest_interceptors(null_interceptor):
+ transport = transports.GeneratorsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.GeneratorsRestInterceptor(),
+ )
+ client = GeneratorsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "post_list_generators"
+ ) as post, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "pre_list_generators"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = generator.ListGeneratorsRequest.pb(
+ generator.ListGeneratorsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = generator.ListGeneratorsResponse.to_json(
+ generator.ListGeneratorsResponse()
+ )
+
+ request = generator.ListGeneratorsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = generator.ListGeneratorsResponse()
+
+ client.list_generators(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_generators_rest_bad_request(
+ transport: str = "rest", request_type=generator.ListGeneratorsRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_generators(request)
+
+
def test_list_generators_rest_flattened():
client = GeneratorsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3200,6 +3522,50 @@ def test_list_generators_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ generator.GetGeneratorRequest,
+ dict,
+ ],
+)
+def test_get_generator_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = generator.Generator.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_generator(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, generator.Generator)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+
+
def test_get_generator_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3319,6 +3685,85 @@ def test_get_generator_rest_unset_required_fields():
assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_generator_rest_interceptors(null_interceptor):
+ transport = transports.GeneratorsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.GeneratorsRestInterceptor(),
+ )
+ client = GeneratorsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "post_get_generator"
+ ) as post, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "pre_get_generator"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = generator.GetGeneratorRequest.pb(generator.GetGeneratorRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = generator.Generator.to_json(generator.Generator())
+
+ request = generator.GetGeneratorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = generator.Generator()
+
+ client.get_generator(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_generator_rest_bad_request(
+ transport: str = "rest", request_type=generator.GetGeneratorRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_generator(request)
+
+
def test_get_generator_rest_flattened():
client = GeneratorsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3378,21 +3823,146 @@ def test_get_generator_rest_flattened_error(transport: str = "rest"):
)
-def test_create_generator_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_get_generator_rest_error():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
- # Ensure method has been cached
- assert client._transport.create_generator in client._transport._wrapped_methods
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_generator.CreateGeneratorRequest,
+ dict,
+ ],
+)
+def test_create_generator_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["generator"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "prompt_text": {"text": "text_value"},
+ "placeholders": [{"id": "id_value", "name": "name_value"}],
+ "llm_model_settings": {
+ "model": "model_value",
+ "prompt_text": "prompt_text_value",
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_generator.CreateGeneratorRequest.meta.fields["generator"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["generator"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["generator"][field])):
+ del request_init["generator"][field][i][subfield]
+ else:
+ del request_init["generator"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_generator.Generator.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_generator(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_generator.Generator)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+
+
+def test_create_generator_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_generator in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
@@ -3510,6 +4080,87 @@ def test_create_generator_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_generator_rest_interceptors(null_interceptor):
+ transport = transports.GeneratorsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.GeneratorsRestInterceptor(),
+ )
+ client = GeneratorsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "post_create_generator"
+ ) as post, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "pre_create_generator"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_generator.CreateGeneratorRequest.pb(
+ gcdc_generator.CreateGeneratorRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_generator.Generator.to_json(
+ gcdc_generator.Generator()
+ )
+
+ request = gcdc_generator.CreateGeneratorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_generator.Generator()
+
+ client.create_generator(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_generator_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_generator.CreateGeneratorRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_generator(request)
+
+
def test_create_generator_rest_flattened():
client = GeneratorsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3569,33 +4220,162 @@ def test_create_generator_rest_flattened_error(transport: str = "rest"):
)
-def test_update_generator_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+def test_create_generator_rest_error():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Ensure method has been cached
- assert client._transport.update_generator in client._transport._wrapped_methods
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.update_generator
- ] = mock_rpc
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_generator.UpdateGeneratorRequest,
+ dict,
+ ],
+)
+def test_update_generator_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- request = {}
- client.update_generator(request)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "generator": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ }
+ request_init["generator"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4",
+ "display_name": "display_name_value",
+ "prompt_text": {"text": "text_value"},
+ "placeholders": [{"id": "id_value", "name": "name_value"}],
+ "llm_model_settings": {
+ "model": "model_value",
+ "prompt_text": "prompt_text_value",
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_generator.UpdateGeneratorRequest.meta.fields["generator"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["generator"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["generator"][field])):
+ del request_init["generator"][field][i][subfield]
+ else:
+ del request_init["generator"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_generator.Generator(
+ name="name_value",
+ display_name="display_name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_generator.Generator.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_generator(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_generator.Generator)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+
+
+def test_update_generator_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_generator in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_generator
+ ] = mock_rpc
+
+ request = {}
+ client.update_generator(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
@@ -3701,6 +4481,91 @@ def test_update_generator_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_generator_rest_interceptors(null_interceptor):
+ transport = transports.GeneratorsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.GeneratorsRestInterceptor(),
+ )
+ client = GeneratorsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "post_update_generator"
+ ) as post, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "pre_update_generator"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_generator.UpdateGeneratorRequest.pb(
+ gcdc_generator.UpdateGeneratorRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_generator.Generator.to_json(
+ gcdc_generator.Generator()
+ )
+
+ request = gcdc_generator.UpdateGeneratorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_generator.Generator()
+
+ client.update_generator(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_generator_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_generator.UpdateGeneratorRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "generator": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_generator(request)
+
+
def test_update_generator_rest_flattened():
client = GeneratorsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3764,6 +4629,49 @@ def test_update_generator_rest_flattened_error(transport: str = "rest"):
)
+def test_update_generator_rest_error():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ generator.DeleteGeneratorRequest,
+ dict,
+ ],
+)
+def test_delete_generator_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_generator(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_generator_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3884,18 +4792,93 @@ def test_delete_generator_rest_unset_required_fields():
assert set(unset_fields) == (set(("force",)) & set(("name",)))
-def test_delete_generator_rest_flattened():
- client = GeneratorsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_generator_rest_interceptors(null_interceptor):
+ transport = transports.GeneratorsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.GeneratorsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
+ client = GeneratorsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.GeneratorsRestInterceptor, "pre_delete_generator"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = generator.DeleteGeneratorRequest.pb(
+ generator.DeleteGeneratorRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = generator.DeleteGeneratorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_generator(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_generator_rest_bad_request(
+ transport: str = "rest", request_type=generator.DeleteGeneratorRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_generator(request)
+
+
+def test_delete_generator_rest_flattened():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
sample_request = {
"name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
}
@@ -3941,6 +4924,12 @@ def test_delete_generator_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_generator_rest_error():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.GeneratorsGrpcTransport(
@@ -4030,1436 +5019,21 @@ def test_transport_adc(transport_class):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = GeneratorsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_generators_empty_call_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_generators), "__call__") as call:
- call.return_value = generator.ListGeneratorsResponse()
- client.list_generators(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.ListGeneratorsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_generator_empty_call_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_generator), "__call__") as call:
- call.return_value = generator.Generator()
- client.get_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.GetGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_generator_empty_call_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_generator), "__call__") as call:
- call.return_value = gcdc_generator.Generator()
- client.create_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.CreateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_generator_empty_call_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_generator), "__call__") as call:
- call.return_value = gcdc_generator.Generator()
- client.update_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.UpdateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_generator_empty_call_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_generator), "__call__") as call:
- call.return_value = None
- client.delete_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.DeleteGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = GeneratorsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_generators_empty_call_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_generators), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- generator.ListGeneratorsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_generators(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.ListGeneratorsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_generator_empty_call_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_generator), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.get_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.GetGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_generator_empty_call_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_generator), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.create_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.CreateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_generator_empty_call_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_generator), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.update_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.UpdateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_generator_empty_call_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_generator), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.DeleteGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = GeneratorsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_generators_rest_bad_request(request_type=generator.ListGeneratorsRequest):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_generators(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- generator.ListGeneratorsRequest,
- dict,
- ],
-)
-def test_list_generators_rest_call_success(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = generator.ListGeneratorsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = generator.ListGeneratorsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_generators(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListGeneratorsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_generators_rest_interceptors(null_interceptor):
- transport = transports.GeneratorsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.GeneratorsRestInterceptor(),
- )
- client = GeneratorsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.GeneratorsRestInterceptor, "post_list_generators"
- ) as post, mock.patch.object(
- transports.GeneratorsRestInterceptor, "pre_list_generators"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = generator.ListGeneratorsRequest.pb(
- generator.ListGeneratorsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = generator.ListGeneratorsResponse.to_json(
- generator.ListGeneratorsResponse()
- )
- req.return_value.content = return_value
-
- request = generator.ListGeneratorsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = generator.ListGeneratorsResponse()
-
- client.list_generators(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_generator_rest_bad_request(request_type=generator.GetGeneratorRequest):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_generator(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- generator.GetGeneratorRequest,
- dict,
- ],
-)
-def test_get_generator_rest_call_success(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = generator.Generator.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_generator(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, generator.Generator)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_generator_rest_interceptors(null_interceptor):
- transport = transports.GeneratorsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.GeneratorsRestInterceptor(),
- )
- client = GeneratorsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.GeneratorsRestInterceptor, "post_get_generator"
- ) as post, mock.patch.object(
- transports.GeneratorsRestInterceptor, "pre_get_generator"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = generator.GetGeneratorRequest.pb(generator.GetGeneratorRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = generator.Generator.to_json(generator.Generator())
- req.return_value.content = return_value
-
- request = generator.GetGeneratorRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = generator.Generator()
-
- client.get_generator(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_generator_rest_bad_request(
- request_type=gcdc_generator.CreateGeneratorRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_generator(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_generator.CreateGeneratorRequest,
- dict,
- ],
-)
-def test_create_generator_rest_call_success(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["generator"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "prompt_text": {"text": "text_value"},
- "placeholders": [{"id": "id_value", "name": "name_value"}],
- "llm_model_settings": {
- "model": "model_value",
- "prompt_text": "prompt_text_value",
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_generator.CreateGeneratorRequest.meta.fields["generator"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["generator"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["generator"][field])):
- del request_init["generator"][field][i][subfield]
- else:
- del request_init["generator"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_generator.Generator.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_generator(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_generator.Generator)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_generator_rest_interceptors(null_interceptor):
- transport = transports.GeneratorsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.GeneratorsRestInterceptor(),
- )
- client = GeneratorsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.GeneratorsRestInterceptor, "post_create_generator"
- ) as post, mock.patch.object(
- transports.GeneratorsRestInterceptor, "pre_create_generator"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_generator.CreateGeneratorRequest.pb(
- gcdc_generator.CreateGeneratorRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_generator.Generator.to_json(gcdc_generator.Generator())
- req.return_value.content = return_value
-
- request = gcdc_generator.CreateGeneratorRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_generator.Generator()
-
- client.create_generator(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_generator_rest_bad_request(
- request_type=gcdc_generator.UpdateGeneratorRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "generator": {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_generator(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_generator.UpdateGeneratorRequest,
- dict,
- ],
-)
-def test_update_generator_rest_call_success(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "generator": {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- }
- request_init["generator"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4",
- "display_name": "display_name_value",
- "prompt_text": {"text": "text_value"},
- "placeholders": [{"id": "id_value", "name": "name_value"}],
- "llm_model_settings": {
- "model": "model_value",
- "prompt_text": "prompt_text_value",
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_generator.UpdateGeneratorRequest.meta.fields["generator"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["generator"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["generator"][field])):
- del request_init["generator"][field][i][subfield]
- else:
- del request_init["generator"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_generator.Generator(
- name="name_value",
- display_name="display_name_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_generator.Generator.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_generator(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_generator.Generator)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_generator_rest_interceptors(null_interceptor):
- transport = transports.GeneratorsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.GeneratorsRestInterceptor(),
- )
- client = GeneratorsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.GeneratorsRestInterceptor, "post_update_generator"
- ) as post, mock.patch.object(
- transports.GeneratorsRestInterceptor, "pre_update_generator"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_generator.UpdateGeneratorRequest.pb(
- gcdc_generator.UpdateGeneratorRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_generator.Generator.to_json(gcdc_generator.Generator())
- req.return_value.content = return_value
-
- request = gcdc_generator.UpdateGeneratorRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_generator.Generator()
-
- client.update_generator(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_generator_rest_bad_request(
- request_type=generator.DeleteGeneratorRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_generator(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- generator.DeleteGeneratorRequest,
- dict,
- ],
-)
-def test_delete_generator_rest_call_success(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/generators/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_generator(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_generator_rest_interceptors(null_interceptor):
- transport = transports.GeneratorsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.GeneratorsRestInterceptor(),
- )
- client = GeneratorsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.GeneratorsRestInterceptor, "pre_delete_generator"
- ) as pre:
- pre.assert_not_called()
- pb_message = generator.DeleteGeneratorRequest.pb(
- generator.DeleteGeneratorRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = generator.DeleteGeneratorRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_generator(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_generators_empty_call_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_generators), "__call__") as call:
- client.list_generators(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.ListGeneratorsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_generator_empty_call_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_generator), "__call__") as call:
- client.get_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.GetGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_generator_empty_call_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_generator), "__call__") as call:
- client.create_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.CreateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_generator_empty_call_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_generator), "__call__") as call:
- client.update_generator(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_generator.UpdateGeneratorRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_generator_empty_call_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_generator), "__call__") as call:
- client.delete_generator(request=None)
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = generator.DeleteGeneratorRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = GeneratorsClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -5951,115 +5525,415 @@ def test_parse_common_billing_account_path():
}
path = GeneratorsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = GeneratorsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = GeneratorsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = GeneratorsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = GeneratorsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GeneratorsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = GeneratorsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = GeneratorsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GeneratorsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = GeneratorsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = GeneratorsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GeneratorsClient.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 = GeneratorsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = GeneratorsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GeneratorsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.GeneratorsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.GeneratorsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = GeneratorsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = GeneratorsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = GeneratorsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = GeneratorsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = GeneratorsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = GeneratorsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = GeneratorsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = GeneratorsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = GeneratorsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = GeneratorsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = GeneratorsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = GeneratorsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = GeneratorsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = GeneratorsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.GeneratorsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.GeneratorsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = GeneratorsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6089,7 +5963,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6142,7 +6016,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6187,7 +6061,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6228,7 +6102,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6283,7 +6157,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6330,7 +6204,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6373,7 +6247,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6428,7 +6302,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6475,7 +6349,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -6518,7 +6392,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6573,7 +6447,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6620,7 +6494,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6663,7 +6537,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6715,7 +6589,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = GeneratorsAsyncClient(credentials=async_anonymous_credentials())
+ client = GeneratorsAsyncClient(credentials=ga_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.
@@ -6761,7 +6635,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6777,41 +6651,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = GeneratorsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = GeneratorsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = GeneratorsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py
index d68aa8ee2ee2..6cd1ba74091b 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -63,6 +45,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.intents import (
IntentsAsyncClient,
@@ -75,24 +65,10 @@
from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1126,6 +1102,25 @@ def test_list_intents(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_intents_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_intents), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ListIntentsRequest()
+
+
def test_list_intents_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1193,6 +1188,29 @@ def test_list_intents_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_intents_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_intents), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ intent.ListIntentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ListIntentsRequest()
+
+
@pytest.mark.asyncio
async def test_list_intents_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1201,7 +1219,7 @@ async def test_list_intents_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1216,23 +1234,27 @@ async def test_list_intents_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_intents
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_intents(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_intents(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1240,7 +1262,7 @@ async def test_list_intents_async(
transport: str = "grpc_asyncio", request_type=intent.ListIntentsRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1306,7 +1328,7 @@ def test_list_intents_field_headers():
@pytest.mark.asyncio
async def test_list_intents_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1376,7 +1398,7 @@ def test_list_intents_flattened_error():
@pytest.mark.asyncio
async def test_list_intents_flattened_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1405,7 +1427,7 @@ async def test_list_intents_flattened_async():
@pytest.mark.asyncio
async def test_list_intents_flattened_error_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1455,16 +1477,12 @@ def test_list_intents_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_intents(request={}, retry=retry, timeout=timeout)
+ pager = client.list_intents(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1515,7 +1533,7 @@ def test_list_intents_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_intents_async_pager():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1565,7 +1583,7 @@ async def test_list_intents_async_pager():
@pytest.mark.asyncio
async def test_list_intents_async_pages():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1655,6 +1673,25 @@ def test_get_intent(request_type, transport: str = "grpc"):
assert response.description == "description_value"
+def test_get_intent_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.GetIntentRequest()
+
+
def test_get_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1720,13 +1757,40 @@ def test_get_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+ )
+ response = await client.get_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.GetIntentRequest()
+
+
@pytest.mark.asyncio
async def test_get_intent_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1741,23 +1805,27 @@ async def test_get_intent_async_use_cached_wrapped_rpc(transport: str = "grpc_as
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1765,7 +1833,7 @@ async def test_get_intent_async(
transport: str = "grpc_asyncio", request_type=intent.GetIntentRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1839,7 +1907,7 @@ def test_get_intent_field_headers():
@pytest.mark.asyncio
async def test_get_intent_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1907,7 +1975,7 @@ def test_get_intent_flattened_error():
@pytest.mark.asyncio
async def test_get_intent_flattened_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1934,7 +2002,7 @@ async def test_get_intent_flattened_async():
@pytest.mark.asyncio
async def test_get_intent_flattened_error_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1990,6 +2058,25 @@ def test_create_intent(request_type, transport: str = "grpc"):
assert response.description == "description_value"
+def test_create_intent_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_intent.CreateIntentRequest()
+
+
def test_create_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2055,6 +2142,33 @@ def test_create_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+ )
+ response = await client.create_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_intent.CreateIntentRequest()
+
+
@pytest.mark.asyncio
async def test_create_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2063,7 +2177,7 @@ async def test_create_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2078,23 +2192,27 @@ async def test_create_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2102,7 +2220,7 @@ async def test_create_intent_async(
transport: str = "grpc_asyncio", request_type=gcdc_intent.CreateIntentRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2176,7 +2294,7 @@ def test_create_intent_field_headers():
@pytest.mark.asyncio
async def test_create_intent_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2249,7 +2367,7 @@ def test_create_intent_flattened_error():
@pytest.mark.asyncio
async def test_create_intent_flattened_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2280,7 +2398,7 @@ async def test_create_intent_flattened_async():
@pytest.mark.asyncio
async def test_create_intent_flattened_error_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2337,6 +2455,25 @@ def test_update_intent(request_type, transport: str = "grpc"):
assert response.description == "description_value"
+def test_update_intent_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_intent.UpdateIntentRequest()
+
+
def test_update_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2400,6 +2537,33 @@ def test_update_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+ )
+ response = await client.update_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_intent.UpdateIntentRequest()
+
+
@pytest.mark.asyncio
async def test_update_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2408,7 +2572,7 @@ async def test_update_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2423,23 +2587,27 @@ async def test_update_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2447,7 +2615,7 @@ async def test_update_intent_async(
transport: str = "grpc_asyncio", request_type=gcdc_intent.UpdateIntentRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2521,7 +2689,7 @@ def test_update_intent_field_headers():
@pytest.mark.asyncio
async def test_update_intent_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2594,7 +2762,7 @@ def test_update_intent_flattened_error():
@pytest.mark.asyncio
async def test_update_intent_flattened_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2625,7 +2793,7 @@ async def test_update_intent_flattened_async():
@pytest.mark.asyncio
async def test_update_intent_flattened_error_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2671,6 +2839,25 @@ def test_delete_intent(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_intent_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.DeleteIntentRequest()
+
+
def test_delete_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2734,6 +2921,25 @@ def test_delete_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.DeleteIntentRequest()
+
+
@pytest.mark.asyncio
async def test_delete_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2742,7 +2948,7 @@ async def test_delete_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2757,23 +2963,27 @@ async def test_delete_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2781,7 +2991,7 @@ async def test_delete_intent_async(
transport: str = "grpc_asyncio", request_type=intent.DeleteIntentRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2842,7 +3052,7 @@ def test_delete_intent_field_headers():
@pytest.mark.asyncio
async def test_delete_intent_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2910,7 +3120,7 @@ def test_delete_intent_flattened_error():
@pytest.mark.asyncio
async def test_delete_intent_flattened_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2937,7 +3147,7 @@ async def test_delete_intent_flattened_async():
@pytest.mark.asyncio
async def test_delete_intent_flattened_error_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2982,6 +3192,25 @@ def test_import_intents(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_import_intents_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.import_intents), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.import_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ImportIntentsRequest()
+
+
def test_import_intents_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3040,9 +3269,8 @@ def test_import_intents_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.import_intents(request)
@@ -3053,14 +3281,35 @@ def test_import_intents_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_import_intents_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
-):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
+async def test_import_intents_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.import_intents), "__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.import_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ImportIntentsRequest()
+
+
+@pytest.mark.asyncio
+async def test_import_intents_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3075,28 +3324,31 @@ async def test_import_intents_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.import_intents
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.import_intents(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.import_intents(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3104,7 +3356,7 @@ async def test_import_intents_async(
transport: str = "grpc_asyncio", request_type=intent.ImportIntentsRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3167,7 +3419,7 @@ def test_import_intents_field_headers():
@pytest.mark.asyncio
async def test_import_intents_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3229,6 +3481,25 @@ def test_export_intents(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_intents_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 = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_intents), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ExportIntentsRequest()
+
+
def test_export_intents_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3287,9 +3558,8 @@ def test_export_intents_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_intents(request)
@@ -3299,6 +3569,27 @@ def test_export_intents_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_intents_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_intents), "__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.export_intents()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == intent.ExportIntentsRequest()
+
+
@pytest.mark.asyncio
async def test_export_intents_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3307,7 +3598,7 @@ async def test_export_intents_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3322,28 +3613,31 @@ async def test_export_intents_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_intents
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_intents(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_intents(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3351,7 +3645,7 @@ async def test_export_intents_async(
transport: str = "grpc_asyncio", request_type=intent.ExportIntentsRequest
):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3414,7 +3708,7 @@ def test_export_intents_field_headers():
@pytest.mark.asyncio
async def test_export_intents_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3443,6 +3737,46 @@ async def test_export_intents_field_headers_async():
) in kw["metadata"]
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ intent.ListIntentsRequest,
+ dict,
+ ],
+)
+def test_list_intents_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = intent.ListIntentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = intent.ListIntentsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_intents(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListIntentsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_intents_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3579,6 +3913,83 @@ def test_list_intents_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_intents_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
+ )
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.IntentsRestInterceptor, "post_list_intents"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_list_intents"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = intent.ListIntentsRequest.pb(intent.ListIntentsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = intent.ListIntentsResponse.to_json(
+ intent.ListIntentsResponse()
+ )
+
+ request = intent.ListIntentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = intent.ListIntentsResponse()
+
+ client.list_intents(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_intents_rest_bad_request(
+ transport: str = "rest", request_type=intent.ListIntentsRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_intents(request)
+
+
def test_list_intents_rest_flattened():
client = IntentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3697,6 +4108,56 @@ def test_list_intents_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ intent.GetIntentRequest,
+ dict,
+ ],
+)
+def test_get_intent_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = intent.Intent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, intent.Intent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.priority == 898
+ assert response.is_fallback is True
+ assert response.description == "description_value"
+
+
def test_get_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3816,13 +4277,90 @@ def test_get_intent_rest_unset_required_fields():
assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
-def test_get_intent_rest_flattened():
- client = IntentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_intent_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
)
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.IntentsRestInterceptor, "post_get_intent"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_get_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = intent.GetIntentRequest.pb(intent.GetIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = intent.Intent.to_json(intent.Intent())
+
+ request = intent.GetIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = intent.Intent()
+
+ client.get_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_intent_rest_bad_request(
+ transport: str = "rest", request_type=intent.GetIntentRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_intent(request)
+
+
+def test_get_intent_rest_flattened():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
return_value = intent.Intent()
@@ -3875,6 +4413,150 @@ def test_get_intent_rest_flattened_error(transport: str = "rest"):
)
+def test_get_intent_rest_error():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_intent.CreateIntentRequest,
+ dict,
+ ],
+)
+def test_create_intent_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["intent"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "training_phrases": [
+ {
+ "id": "id_value",
+ "parts": [{"text": "text_value", "parameter_id": "parameter_id_value"}],
+ "repeat_count": 1289,
+ }
+ ],
+ "parameters": [
+ {
+ "id": "id_value",
+ "entity_type": "entity_type_value",
+ "is_list": True,
+ "redact": True,
+ }
+ ],
+ "priority": 898,
+ "is_fallback": True,
+ "labels": {},
+ "description": "description_value",
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_intent.CreateIntentRequest.meta.fields["intent"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["intent"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["intent"][field])):
+ del request_init["intent"][field][i][subfield]
+ else:
+ del request_init["intent"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_intent.Intent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_intent.Intent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.priority == 898
+ assert response.is_fallback is True
+ assert response.description == "description_value"
+
+
def test_create_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4005,35 +4687,112 @@ def test_create_intent_rest_unset_required_fields():
)
-def test_create_intent_rest_flattened():
- client = IntentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_intent_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
)
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.IntentsRestInterceptor, "post_create_intent"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_create_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_intent.CreateIntentRequest.pb(
+ gcdc_intent.CreateIntentRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_intent.Intent()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_intent.Intent.to_json(gcdc_intent.Intent())
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = gcdc_intent.CreateIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_intent.Intent()
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- intent=gcdc_intent.Intent(name="name_value"),
+ client.create_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_intent.Intent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_intent_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_intent.CreateIntentRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_intent(request)
+
+
+def test_create_intent_rest_flattened():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_intent.Intent()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ intent=gcdc_intent.Intent(name="name_value"),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_intent.Intent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
client.create_intent(**mock_args)
@@ -4064,6 +4823,154 @@ def test_create_intent_rest_flattened_error(transport: str = "rest"):
)
+def test_create_intent_rest_error():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_intent.UpdateIntentRequest,
+ dict,
+ ],
+)
+def test_update_intent_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "intent": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ }
+ request_init["intent"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4",
+ "display_name": "display_name_value",
+ "training_phrases": [
+ {
+ "id": "id_value",
+ "parts": [{"text": "text_value", "parameter_id": "parameter_id_value"}],
+ "repeat_count": 1289,
+ }
+ ],
+ "parameters": [
+ {
+ "id": "id_value",
+ "entity_type": "entity_type_value",
+ "is_list": True,
+ "redact": True,
+ }
+ ],
+ "priority": 898,
+ "is_fallback": True,
+ "labels": {},
+ "description": "description_value",
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_intent.UpdateIntentRequest.meta.fields["intent"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["intent"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["intent"][field])):
+ del request_init["intent"][field][i][subfield]
+ else:
+ del request_init["intent"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_intent.Intent(
+ name="name_value",
+ display_name="display_name_value",
+ priority=898,
+ is_fallback=True,
+ description="description_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_intent.Intent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_intent.Intent)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.priority == 898
+ assert response.is_fallback is True
+ assert response.description == "description_value"
+
+
def test_update_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4194,41 +5101,122 @@ def test_update_intent_rest_unset_required_fields():
)
-def test_update_intent_rest_flattened():
- client = IntentsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_intent_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_intent.Intent()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "intent": {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- intent=gcdc_intent.Intent(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.IntentsRestInterceptor, "post_update_intent"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_update_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_intent.UpdateIntentRequest.pb(
+ gcdc_intent.UpdateIntentRequest()
)
- mock_args.update(sample_request)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_intent.Intent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_intent.Intent.to_json(gcdc_intent.Intent())
- client.update_intent(**mock_args)
+ request = gcdc_intent.UpdateIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_intent.Intent()
+
+ client.update_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_intent_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_intent.UpdateIntentRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "intent": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_intent(request)
+
+
+def test_update_intent_rest_flattened():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_intent.Intent()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "intent": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ intent=gcdc_intent.Intent(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_intent.Intent.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.update_intent(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
@@ -4257,6 +5245,49 @@ def test_update_intent_rest_flattened_error(transport: str = "rest"):
)
+def test_update_intent_rest_error():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ intent.DeleteIntentRequest,
+ dict,
+ ],
+)
+def test_delete_intent_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4371,6 +5402,77 @@ def test_delete_intent_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_intent_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
+ )
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_delete_intent"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = intent.DeleteIntentRequest.pb(intent.DeleteIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = intent.DeleteIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_intent_rest_bad_request(
+ transport: str = "rest", request_type=intent.DeleteIntentRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_intent(request)
+
+
def test_delete_intent_rest_flattened():
client = IntentsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4428,6 +5530,47 @@ def test_delete_intent_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_intent_rest_error():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ intent.ImportIntentsRequest,
+ dict,
+ ],
+)
+def test_import_intents_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.import_intents(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
def test_import_intents_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4547,35 +5690,155 @@ def test_import_intents_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("parent",)))
-def test_export_intents_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.export_intents in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.export_intents] = mock_rpc
-
- request = {}
- client.export_intents(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_import_intents_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
+ )
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.IntentsRestInterceptor, "post_import_intents"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_import_intents"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = intent.ImportIntentsRequest.pb(intent.ImportIntentsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
+
+ request = intent.ImportIntentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
+
+ client.import_intents(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_import_intents_rest_bad_request(
+ transport: str = "rest", request_type=intent.ImportIntentsRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.import_intents(request)
+
+
+def test_import_intents_rest_error():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ intent.ExportIntentsRequest,
+ dict,
+ ],
+)
+def test_export_intents_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.export_intents(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_export_intents_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.export_intents in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.export_intents] = mock_rpc
+
+ request = {}
+ client.export_intents(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
# Operation methods build a cached wrapper on first rpc call
# subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
@@ -4678,1712 +5941,72 @@ def test_export_intents_rest_unset_required_fields():
)
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = IntentsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = IntentsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = IntentsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = IntentsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = IntentsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.IntentsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.IntentsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.IntentsGrpcTransport,
- transports.IntentsGrpcAsyncIOTransport,
- transports.IntentsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = IntentsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_intents_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_intents), "__call__") as call:
- call.return_value = intent.ListIntentsResponse()
- client.list_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ListIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_intent_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_intent), "__call__") as call:
- call.return_value = intent.Intent()
- client.get_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.GetIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_intent_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_intent), "__call__") as call:
- call.return_value = gcdc_intent.Intent()
- client.create_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.CreateIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_intent_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_intent), "__call__") as call:
- call.return_value = gcdc_intent.Intent()
- client.update_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.UpdateIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_intent_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_intent), "__call__") as call:
- call.return_value = None
- client.delete_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.DeleteIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_intents_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_intents), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.import_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ImportIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_intents_empty_call_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_intents), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ExportIntentsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = IntentsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_intents_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_intents), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- intent.ListIntentsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ListIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_intent_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
- )
- await client.get_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.GetIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_intent_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
- )
- await client.create_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.CreateIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_intent_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
- )
- await client.update_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.UpdateIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_intent_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.DeleteIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_import_intents_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_intents), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.import_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ImportIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_intents_empty_call_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_intents), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.export_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ExportIntentsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = IntentsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_intents_rest_bad_request(request_type=intent.ListIntentsRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_intents(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- intent.ListIntentsRequest,
- dict,
- ],
-)
-def test_list_intents_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = intent.ListIntentsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = intent.ListIntentsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_intents(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListIntentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_intents_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.IntentsRestInterceptor, "post_list_intents"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_list_intents"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = intent.ListIntentsRequest.pb(intent.ListIntentsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = intent.ListIntentsResponse.to_json(intent.ListIntentsResponse())
- req.return_value.content = return_value
-
- request = intent.ListIntentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = intent.ListIntentsResponse()
-
- client.list_intents(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_intent_rest_bad_request(request_type=intent.GetIntentRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- intent.GetIntentRequest,
- dict,
- ],
-)
-def test_get_intent_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = intent.Intent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, intent.Intent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.priority == 898
- assert response.is_fallback is True
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_intent_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.IntentsRestInterceptor, "post_get_intent"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_get_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = intent.GetIntentRequest.pb(intent.GetIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = intent.Intent.to_json(intent.Intent())
- req.return_value.content = return_value
-
- request = intent.GetIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = intent.Intent()
-
- client.get_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_intent_rest_bad_request(request_type=gcdc_intent.CreateIntentRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_intent.CreateIntentRequest,
- dict,
- ],
-)
-def test_create_intent_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["intent"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "training_phrases": [
- {
- "id": "id_value",
- "parts": [{"text": "text_value", "parameter_id": "parameter_id_value"}],
- "repeat_count": 1289,
- }
- ],
- "parameters": [
- {
- "id": "id_value",
- "entity_type": "entity_type_value",
- "is_list": True,
- "redact": True,
- }
- ],
- "priority": 898,
- "is_fallback": True,
- "labels": {},
- "description": "description_value",
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_intent.CreateIntentRequest.meta.fields["intent"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["intent"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["intent"][field])):
- del request_init["intent"][field][i][subfield]
- else:
- del request_init["intent"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_intent.Intent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_intent.Intent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.priority == 898
- assert response.is_fallback is True
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_intent_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.IntentsRestInterceptor, "post_create_intent"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_create_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_intent.CreateIntentRequest.pb(
- gcdc_intent.CreateIntentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_intent.Intent.to_json(gcdc_intent.Intent())
- req.return_value.content = return_value
-
- request = gcdc_intent.CreateIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_intent.Intent()
-
- client.create_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_intent_rest_bad_request(request_type=gcdc_intent.UpdateIntentRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "intent": {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_intent.UpdateIntentRequest,
- dict,
- ],
-)
-def test_update_intent_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "intent": {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- }
- request_init["intent"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4",
- "display_name": "display_name_value",
- "training_phrases": [
- {
- "id": "id_value",
- "parts": [{"text": "text_value", "parameter_id": "parameter_id_value"}],
- "repeat_count": 1289,
- }
- ],
- "parameters": [
- {
- "id": "id_value",
- "entity_type": "entity_type_value",
- "is_list": True,
- "redact": True,
- }
- ],
- "priority": 898,
- "is_fallback": True,
- "labels": {},
- "description": "description_value",
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_intent.UpdateIntentRequest.meta.fields["intent"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["intent"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["intent"][field])):
- del request_init["intent"][field][i][subfield]
- else:
- del request_init["intent"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_intent.Intent(
- name="name_value",
- display_name="display_name_value",
- priority=898,
- is_fallback=True,
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_intent.Intent.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_intent.Intent)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.priority == 898
- assert response.is_fallback is True
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_intent_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.IntentsRestInterceptor, "post_update_intent"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_update_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_intent.UpdateIntentRequest.pb(
- gcdc_intent.UpdateIntentRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_intent.Intent.to_json(gcdc_intent.Intent())
- req.return_value.content = return_value
-
- request = gcdc_intent.UpdateIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_intent.Intent()
-
- client.update_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_intent_rest_bad_request(request_type=intent.DeleteIntentRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- intent.DeleteIntentRequest,
- dict,
- ],
-)
-def test_delete_intent_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/intents/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_intent(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_intent_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_delete_intent"
- ) as pre:
- pre.assert_not_called()
- pb_message = intent.DeleteIntentRequest.pb(intent.DeleteIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = intent.DeleteIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_import_intents_rest_bad_request(request_type=intent.ImportIntentsRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.import_intents(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- intent.ImportIntentsRequest,
- dict,
- ],
-)
-def test_import_intents_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.import_intents(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_import_intents_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.IntentsRestInterceptor, "post_import_intents"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_import_intents"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = intent.ImportIntentsRequest.pb(intent.ImportIntentsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = intent.ImportIntentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.import_intents(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_export_intents_rest_bad_request(request_type=intent.ExportIntentsRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_intents(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- intent.ExportIntentsRequest,
- dict,
- ],
-)
-def test_export_intents_rest_call_success(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_intents(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_intents_rest_interceptors(null_interceptor):
- transport = transports.IntentsRestTransport(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_intents_rest_interceptors(null_interceptor):
+ transport = transports.IntentsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.IntentsRestInterceptor(),
- )
- client = IntentsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.IntentsRestInterceptor, "post_export_intents"
- ) as post, mock.patch.object(
- transports.IntentsRestInterceptor, "pre_export_intents"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = intent.ExportIntentsRequest.pb(intent.ExportIntentsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = intent.ExportIntentsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.export_intents(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ )
+ client = IntentsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.IntentsRestInterceptor, "post_export_intents"
+ ) as post, mock.patch.object(
+ transports.IntentsRestInterceptor, "pre_export_intents"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = intent.ExportIntentsRequest.pb(intent.ExportIntentsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- req.return_value = response_value
+ request = intent.ExportIntentsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- response = client.get_operation(request)
+ client.export_intents(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_export_intents_rest_bad_request(
+ transport: str = "rest", request_type=intent.ExportIntentsRequest
):
client = IntentsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -6391,210 +6014,122 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ client.export_intents(request)
-def test_initialize_client_w_rest():
+def test_export_intents_rest_error():
client = IntentsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_intents_empty_call_rest():
- client = IntentsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_intents), "__call__") as call:
- client.list_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ListIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_intent_empty_call_rest():
- client = IntentsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = IntentsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_intent), "__call__") as call:
- client.get_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.GetIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_intent_empty_call_rest():
- client = IntentsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = IntentsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_intent), "__call__") as call:
- client.create_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.CreateIntentRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = IntentsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_intent_empty_call_rest():
- client = IntentsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_intent), "__call__") as call:
- client.update_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_intent.UpdateIntentRequest()
-
- assert args[0] == request_msg
+ with pytest.raises(ValueError):
+ client = IntentsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_intent_empty_call_rest():
- client = IntentsClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_intent), "__call__") as call:
- client.delete_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.DeleteIntentRequest()
-
- assert args[0] == request_msg
+ client = IntentsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_intents_empty_call_rest():
- client = IntentsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.IntentsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.import_intents), "__call__") as call:
- client.import_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ImportIntentsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_intents_empty_call_rest():
- client = IntentsClient(
+ transport = transports.IntentsGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_intents), "__call__") as call:
- client.export_intents(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = intent.ExportIntentsRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.IntentsGrpcTransport,
+ transports.IntentsGrpcAsyncIOTransport,
+ transports.IntentsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_intents_rest_lro_client():
- client = IntentsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = IntentsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6840,15 +6375,32 @@ def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class):
)
-def test_intents_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.IntentsRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_intents_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.IntentsRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_intents_rest_lro_client():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -7162,115 +6714,415 @@ def test_parse_common_billing_account_path():
}
path = IntentsClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = IntentsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = IntentsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = IntentsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = IntentsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = IntentsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = IntentsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nautilus",
+ }
+ path = IntentsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = IntentsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "scallop"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = IntentsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "abalone",
+ }
+ path = IntentsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = IntentsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = IntentsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = IntentsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = IntentsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.IntentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.IntentsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = IntentsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = IntentsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = IntentsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = IntentsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = IntentsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = IntentsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = IntentsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = IntentsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = IntentsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = IntentsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = IntentsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = IntentsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = IntentsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = IntentsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.IntentsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.IntentsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = IntentsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -7300,7 +7152,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7353,7 +7205,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7398,7 +7250,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -7439,7 +7291,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7494,7 +7346,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7541,7 +7393,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -7584,7 +7436,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7639,7 +7491,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7686,7 +7538,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -7729,7 +7581,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7784,7 +7636,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7831,7 +7683,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7874,7 +7726,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7926,7 +7778,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = IntentsAsyncClient(credentials=async_anonymous_credentials())
+ client = IntentsAsyncClient(credentials=ga_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.
@@ -7972,7 +7824,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7988,41 +7840,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = IntentsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = IntentsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = IntentsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py
index 64033b56c403..b411c16e6e3a 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -55,7 +37,15 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.pages import (
PagesAsyncClient,
@@ -74,24 +64,10 @@
from google.cloud.dialogflowcx_v3beta1.types import response_message, tool_call
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1120,6 +1096,25 @@ def test_list_pages(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_pages_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 = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_pages), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_pages()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.ListPagesRequest()
+
+
def test_list_pages_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1187,13 +1182,36 @@ def test_list_pages_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_pages_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_pages), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ page.ListPagesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_pages()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.ListPagesRequest()
+
+
@pytest.mark.asyncio
async def test_list_pages_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1208,23 +1226,27 @@ async def test_list_pages_async_use_cached_wrapped_rpc(transport: str = "grpc_as
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_pages
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_pages(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_pages(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1232,7 +1254,7 @@ async def test_list_pages_async(
transport: str = "grpc_asyncio", request_type=page.ListPagesRequest
):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1298,7 +1320,7 @@ def test_list_pages_field_headers():
@pytest.mark.asyncio
async def test_list_pages_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1368,7 +1390,7 @@ def test_list_pages_flattened_error():
@pytest.mark.asyncio
async def test_list_pages_flattened_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1397,7 +1419,7 @@ async def test_list_pages_flattened_async():
@pytest.mark.asyncio
async def test_list_pages_flattened_error_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1447,16 +1469,12 @@ def test_list_pages_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_pages(request={}, retry=retry, timeout=timeout)
+ pager = client.list_pages(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1507,7 +1525,7 @@ def test_list_pages_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_pages_async_pager():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1557,7 +1575,7 @@ async def test_list_pages_async_pager():
@pytest.mark.asyncio
async def test_list_pages_async_pages():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1645,6 +1663,25 @@ def test_get_page(request_type, transport: str = "grpc"):
assert response.transition_route_groups == ["transition_route_groups_value"]
+def test_get_page_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 = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_page), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.GetPageRequest()
+
+
def test_get_page_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1710,13 +1747,39 @@ def test_get_page_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_page_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_page), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ page.Page(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.get_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.GetPageRequest()
+
+
@pytest.mark.asyncio
async def test_get_page_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1731,23 +1794,27 @@ async def test_get_page_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_page
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_page(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_page(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1755,7 +1822,7 @@ async def test_get_page_async(
transport: str = "grpc_asyncio", request_type=page.GetPageRequest
):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1827,7 +1894,7 @@ def test_get_page_field_headers():
@pytest.mark.asyncio
async def test_get_page_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1895,7 +1962,7 @@ def test_get_page_flattened_error():
@pytest.mark.asyncio
async def test_get_page_flattened_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1922,7 +1989,7 @@ async def test_get_page_flattened_async():
@pytest.mark.asyncio
async def test_get_page_flattened_error_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1976,6 +2043,25 @@ def test_create_page(request_type, transport: str = "grpc"):
assert response.transition_route_groups == ["transition_route_groups_value"]
+def test_create_page_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 = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_page), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_page.CreatePageRequest()
+
+
def test_create_page_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2041,6 +2127,32 @@ def test_create_page_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_page_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_page), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_page.Page(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.create_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_page.CreatePageRequest()
+
+
@pytest.mark.asyncio
async def test_create_page_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2049,7 +2161,7 @@ async def test_create_page_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2064,23 +2176,27 @@ async def test_create_page_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_page
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_page(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_page(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2088,7 +2204,7 @@ async def test_create_page_async(
transport: str = "grpc_asyncio", request_type=gcdc_page.CreatePageRequest
):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2160,7 +2276,7 @@ def test_create_page_field_headers():
@pytest.mark.asyncio
async def test_create_page_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2233,7 +2349,7 @@ def test_create_page_flattened_error():
@pytest.mark.asyncio
async def test_create_page_flattened_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2264,7 +2380,7 @@ async def test_create_page_flattened_async():
@pytest.mark.asyncio
async def test_create_page_flattened_error_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2319,6 +2435,25 @@ def test_update_page(request_type, transport: str = "grpc"):
assert response.transition_route_groups == ["transition_route_groups_value"]
+def test_update_page_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 = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_page), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_page.UpdatePageRequest()
+
+
def test_update_page_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2382,6 +2517,32 @@ def test_update_page_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_page_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_page), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_page.Page(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+ )
+ response = await client.update_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_page.UpdatePageRequest()
+
+
@pytest.mark.asyncio
async def test_update_page_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2390,7 +2551,7 @@ async def test_update_page_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2405,23 +2566,27 @@ async def test_update_page_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_page
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_page(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_page(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2429,7 +2594,7 @@ async def test_update_page_async(
transport: str = "grpc_asyncio", request_type=gcdc_page.UpdatePageRequest
):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2501,7 +2666,7 @@ def test_update_page_field_headers():
@pytest.mark.asyncio
async def test_update_page_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2574,7 +2739,7 @@ def test_update_page_flattened_error():
@pytest.mark.asyncio
async def test_update_page_flattened_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2605,7 +2770,7 @@ async def test_update_page_flattened_async():
@pytest.mark.asyncio
async def test_update_page_flattened_error_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2651,6 +2816,25 @@ def test_delete_page(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_page_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 = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_page), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.DeletePageRequest()
+
+
def test_delete_page_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2714,6 +2898,25 @@ def test_delete_page_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_page_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_page), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_page()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == page.DeletePageRequest()
+
+
@pytest.mark.asyncio
async def test_delete_page_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2722,7 +2925,7 @@ async def test_delete_page_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2737,23 +2940,27 @@ async def test_delete_page_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_page
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_page(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_page(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2761,7 +2968,7 @@ async def test_delete_page_async(
transport: str = "grpc_asyncio", request_type=page.DeletePageRequest
):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2822,7 +3029,7 @@ def test_delete_page_field_headers():
@pytest.mark.asyncio
async def test_delete_page_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2890,7 +3097,7 @@ def test_delete_page_flattened_error():
@pytest.mark.asyncio
async def test_delete_page_flattened_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2917,7 +3124,7 @@ async def test_delete_page_flattened_async():
@pytest.mark.asyncio
async def test_delete_page_flattened_error_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2929,20 +3136,62 @@ async def test_delete_page_flattened_error_async():
)
-def test_list_pages_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ page.ListPagesRequest,
+ dict,
+ ],
+)
+def test_list_pages_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Ensure method has been cached
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = page.ListPagesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = page.ListPagesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_pages(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListPagesPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_pages_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
assert client._transport.list_pages in client._transport._wrapped_methods
# Replace cached wrapped function with mock
@@ -3063,6 +3312,85 @@ def test_list_pages_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_pages_rest_interceptors(null_interceptor):
+ transport = transports.PagesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
+ )
+ client = PagesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PagesRestInterceptor, "post_list_pages"
+ ) as post, mock.patch.object(
+ transports.PagesRestInterceptor, "pre_list_pages"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = page.ListPagesRequest.pb(page.ListPagesRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = page.ListPagesResponse.to_json(
+ page.ListPagesResponse()
+ )
+
+ request = page.ListPagesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = page.ListPagesResponse()
+
+ client.list_pages(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_pages_rest_bad_request(
+ transport: str = "rest", request_type=page.ListPagesRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_pages(request)
+
+
def test_list_pages_rest_flattened():
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3185,6 +3513,54 @@ def test_list_pages_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ page.GetPageRequest,
+ dict,
+ ],
+)
+def test_get_page_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = page.Page(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ transition_route_groups=["transition_route_groups_value"],
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = page.Page.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_page(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, page.Page)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.transition_route_groups == ["transition_route_groups_value"]
+
+
def test_get_page_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3304,6 +3680,83 @@ def test_get_page_rest_unset_required_fields():
assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_page_rest_interceptors(null_interceptor):
+ transport = transports.PagesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
+ )
+ client = PagesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PagesRestInterceptor, "post_get_page"
+ ) as post, mock.patch.object(
+ transports.PagesRestInterceptor, "pre_get_page"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = page.GetPageRequest.pb(page.GetPageRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = page.Page.to_json(page.Page())
+
+ request = page.GetPageRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = page.Page()
+
+ client.get_page(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_page_rest_bad_request(
+ transport: str = "rest", request_type=page.GetPageRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_page(request)
+
+
def test_get_page_rest_flattened():
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3363,1193 +3816,10 @@ def test_get_page_rest_flattened_error(transport: str = "rest"):
)
-def test_create_page_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.create_page in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.create_page] = mock_rpc
-
- request = {}
- client.create_page(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.create_page(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_create_page_rest_required_fields(request_type=gcdc_page.CreatePageRequest):
- transport_class = transports.PagesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_page._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_page._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("language_code",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_page.Page()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_page.Page.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.create_page(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_page_rest_unset_required_fields():
- transport = transports.PagesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_page._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("languageCode",))
- & set(
- (
- "parent",
- "page",
- )
- )
- )
-
-
-def test_create_page_rest_flattened():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_page.Page()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- page=gcdc_page.Page(name="name_value"),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_page.Page.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.create_page(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/pages"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_page_rest_flattened_error(transport: str = "rest"):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_page(
- gcdc_page.CreatePageRequest(),
- parent="parent_value",
- page=gcdc_page.Page(name="name_value"),
- )
-
-
-def test_update_page_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_page in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.update_page] = mock_rpc
-
- request = {}
- client.update_page(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.update_page(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_update_page_rest_required_fields(request_type=gcdc_page.UpdatePageRequest):
- transport_class = transports.PagesRestTransport
-
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_page._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_page._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "language_code",
- "update_mask",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
-
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_page.Page()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "patch",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_page.Page.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.update_page(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_page_rest_unset_required_fields():
- transport = transports.PagesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_page._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "languageCode",
- "updateMask",
- )
- )
- & set(("page",))
- )
-
-
-def test_update_page_rest_flattened():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_page.Page()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "page": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- page=gcdc_page.Page(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_page.Page.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_page(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{page.name=projects/*/locations/*/agents/*/flows/*/pages/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_page_rest_flattened_error(transport: str = "rest"):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_page(
- gcdc_page.UpdatePageRequest(),
- page=gcdc_page.Page(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_delete_page_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.delete_page in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.delete_page] = mock_rpc
-
- request = {}
- client.delete_page(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.delete_page(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_delete_page_rest_required_fields(request_type=page.DeletePageRequest):
- transport_class = transports.PagesRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_page._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_page._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("force",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = None
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "delete",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.delete_page(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_page_rest_unset_required_fields():
- transport = transports.PagesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_page._get_unset_required_fields({})
- assert set(unset_fields) == (set(("force",)) & set(("name",)))
-
-
-def test_delete_page_rest_flattened():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_page(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/pages/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_page_rest_flattened_error(transport: str = "rest"):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_page(
- page.DeletePageRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PagesClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = PagesClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = PagesClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PagesClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = PagesClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.PagesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.PagesGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.PagesGrpcTransport,
- transports.PagesGrpcAsyncIOTransport,
- transports.PagesRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = PagesClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_pages_empty_call_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_pages), "__call__") as call:
- call.return_value = page.ListPagesResponse()
- client.list_pages(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.ListPagesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_page_empty_call_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_page), "__call__") as call:
- call.return_value = page.Page()
- client.get_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.GetPageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_page_empty_call_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_page), "__call__") as call:
- call.return_value = gcdc_page.Page()
- client.create_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.CreatePageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_page_empty_call_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_page), "__call__") as call:
- call.return_value = gcdc_page.Page()
- client.update_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.UpdatePageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_page_empty_call_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_page), "__call__") as call:
- call.return_value = None
- client.delete_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.DeletePageRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = PagesAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_pages_empty_call_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_pages), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- page.ListPagesResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_pages(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.ListPagesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_page_empty_call_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_page), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- page.Page(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- )
- )
- await client.get_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.GetPageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_page_empty_call_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_page), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_page.Page(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- )
- )
- await client.create_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.CreatePageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_page_empty_call_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_page), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_page.Page(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- )
- )
- await client.update_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.UpdatePageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_page_empty_call_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_page), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.DeletePageRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = PagesClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_pages_rest_bad_request(request_type=page.ListPagesRequest):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_pages(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- page.ListPagesRequest,
- dict,
- ],
-)
-def test_list_pages_rest_call_success(request_type):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = page.ListPagesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = page.ListPagesResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_pages(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListPagesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_pages_rest_interceptors(null_interceptor):
- transport = transports.PagesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
- )
- client = PagesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PagesRestInterceptor, "post_list_pages"
- ) as post, mock.patch.object(
- transports.PagesRestInterceptor, "pre_list_pages"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = page.ListPagesRequest.pb(page.ListPagesRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = page.ListPagesResponse.to_json(page.ListPagesResponse())
- req.return_value.content = return_value
-
- request = page.ListPagesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = page.ListPagesResponse()
-
- client.list_pages(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_page_rest_bad_request(request_type=page.GetPageRequest):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_page(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- page.GetPageRequest,
- dict,
- ],
-)
-def test_get_page_rest_call_success(request_type):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = page.Page(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- transition_route_groups=["transition_route_groups_value"],
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = page.Page.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_page(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, page.Page)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.transition_route_groups == ["transition_route_groups_value"]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_page_rest_interceptors(null_interceptor):
- transport = transports.PagesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
- )
- client = PagesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PagesRestInterceptor, "post_get_page"
- ) as post, mock.patch.object(
- transports.PagesRestInterceptor, "pre_get_page"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = page.GetPageRequest.pb(page.GetPageRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = page.Page.to_json(page.Page())
- req.return_value.content = return_value
-
- request = page.GetPageRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = page.Page()
-
- client.get_page(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_page_rest_bad_request(request_type=gcdc_page.CreatePageRequest):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_page(request)
+def test_get_page_rest_error():
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -4559,9 +3829,10 @@ def test_create_page_rest_bad_request(request_type=gcdc_page.CreatePageRequest):
dict,
],
)
-def test_create_page_rest_call_success(request_type):
+def test_create_page_rest(request_type):
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -4655,7 +3926,6 @@ def test_create_page_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -4676,7 +3946,6 @@ def test_create_page_rest_call_success(request_type):
"trigger_fulfillment": {},
"target_page": "target_page_value",
"target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
}
],
},
@@ -4793,13 +4062,13 @@ def get_message_fields(field):
)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = gcdc_page.Page.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.create_page(request)
@@ -4811,6 +4080,134 @@ def get_message_fields(field):
assert response.transition_route_groups == ["transition_route_groups_value"]
+def test_create_page_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_page in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_page] = mock_rpc
+
+ request = {}
+ client.create_page(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_page(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_create_page_rest_required_fields(request_type=gcdc_page.CreatePageRequest):
+ transport_class = transports.PagesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).create_page._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).create_page._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("language_code",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_page.Page()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = gcdc_page.Page.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.create_page(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_create_page_rest_unset_required_fields():
+ transport = transports.PagesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.create_page._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("languageCode",))
+ & set(
+ (
+ "parent",
+ "page",
+ )
+ )
+ )
+
+
@pytest.mark.parametrize("null_interceptor", [True, False])
def test_create_page_rest_interceptors(null_interceptor):
transport = transports.PagesRestTransport(
@@ -4818,7 +4215,6 @@ def test_create_page_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
)
client = PagesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -4838,10 +4234,10 @@ def test_create_page_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_page.Page.to_json(gcdc_page.Page())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_page.Page.to_json(gcdc_page.Page())
request = gcdc_page.CreatePageRequest()
metadata = [
@@ -4863,30 +4259,97 @@ def test_create_page_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_update_page_rest_bad_request(request_type=gcdc_page.UpdatePageRequest):
+def test_create_page_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_page.CreatePageRequest
+):
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "page": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
}
request = request_type(**request_init)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_page(request)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_page(request)
+
+
+def test_create_page_rest_flattened():
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_page.Page()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ page=gcdc_page.Page(name="name_value"),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_page.Page.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.create_page(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/pages"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_create_page_rest_flattened_error(transport: str = "rest"):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_page(
+ gcdc_page.CreatePageRequest(),
+ parent="parent_value",
+ page=gcdc_page.Page(name="name_value"),
+ )
+
+
+def test_create_page_rest_error():
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -4896,9 +4359,10 @@ def test_update_page_rest_bad_request(request_type=gcdc_page.UpdatePageRequest):
dict,
],
)
-def test_update_page_rest_call_success(request_type):
+def test_update_page_rest(request_type):
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -4994,7 +4458,6 @@ def test_update_page_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -5015,7 +4478,6 @@ def test_update_page_rest_call_success(request_type):
"trigger_fulfillment": {},
"target_page": "target_page_value",
"target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
}
],
},
@@ -5132,13 +4594,13 @@ def get_message_fields(field):
)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = gcdc_page.Page.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.update_page(request)
@@ -5150,6 +4612,134 @@ def get_message_fields(field):
assert response.transition_route_groups == ["transition_route_groups_value"]
+def test_update_page_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_page in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_page] = mock_rpc
+
+ request = {}
+ client.update_page(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_page(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_page_rest_required_fields(request_type=gcdc_page.UpdatePageRequest):
+ transport_class = transports.PagesRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_page._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_page._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "language_code",
+ "update_mask",
+ )
+ )
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_page.Page()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "patch",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = gcdc_page.Page.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.update_page(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_update_page_rest_unset_required_fields():
+ transport = transports.PagesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.update_page._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "languageCode",
+ "updateMask",
+ )
+ )
+ & set(("page",))
+ )
+
+
@pytest.mark.parametrize("null_interceptor", [True, False])
def test_update_page_rest_interceptors(null_interceptor):
transport = transports.PagesRestTransport(
@@ -5157,7 +4747,6 @@ def test_update_page_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
)
client = PagesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -5177,10 +4766,10 @@ def test_update_page_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_page.Page.to_json(gcdc_page.Page())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_page.Page.to_json(gcdc_page.Page())
request = gcdc_page.UpdatePageRequest()
metadata = [
@@ -5202,13 +4791,19 @@ def test_update_page_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_delete_page_rest_bad_request(request_type=page.DeletePageRequest):
+def test_update_page_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_page.UpdatePageRequest
+):
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ "page": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
}
request = request_type(**request_init)
@@ -5217,494 +4812,473 @@ def test_delete_page_rest_bad_request(request_type=page.DeletePageRequest):
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.delete_page(request)
+ client.update_page(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- page.DeletePageRequest,
- dict,
- ],
-)
-def test_delete_page_rest_call_success(request_type):
+def test_update_page_rest_flattened():
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = gcdc_page.Page()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "page": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ page=gcdc_page.Page(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = gcdc_page.Page.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_page(request)
- # Establish that the response is the type that we expect.
- assert response is None
+ client.update_page(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{page.name=projects/*/locations/*/agents/*/flows/*/pages/*}"
+ % client.transport._host,
+ args[1],
+ )
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_page_rest_interceptors(null_interceptor):
- transport = transports.PagesRestTransport(
+def test_update_page_rest_flattened_error(transport: str = "rest"):
+ client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
+ transport=transport,
)
- client = PagesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PagesRestInterceptor, "pre_delete_page"
- ) as pre:
- pre.assert_not_called()
- pb_message = page.DeletePageRequest.pb(page.DeletePageRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = page.DeletePageRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_page(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
- pre.assert_called_once()
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_page(
+ gcdc_page.UpdatePageRequest(),
+ page=gcdc_page.Page(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_update_page_rest_error():
client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.GetLocationRequest,
+ page.DeletePageRequest,
dict,
],
)
-def test_get_location_rest(request_type):
+def test_delete_page_rest(request_type):
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = None
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.get_location(request)
+ response = client.delete_page(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ assert response is None
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+def test_delete_page_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_page in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_page] = mock_rpc
+
+ request = {}
+ client.delete_page(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_page(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_delete_page_rest_required_fields(request_type=page.DeletePageRequest):
+ transport_class = transports.PagesRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_page._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_page._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("force",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "delete",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- req.return_value = response_value
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- response = client.list_locations(request)
+ response = client.delete_page(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_delete_page_rest_unset_required_fields():
+ transport = transports.PagesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ unset_fields = transport.delete_page._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("force",)) & set(("name",)))
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = PagesClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_page_rest_interceptors(null_interceptor):
+ transport = transports.PagesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PagesRestInterceptor(),
)
+ client = PagesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PagesRestInterceptor, "pre_delete_page"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = page.DeletePageRequest.pb(page.DeletePageRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- req.return_value = response_value
+ request = page.DeletePageRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- response = client.cancel_operation(request)
+ client.delete_page(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert response is None
+ pre.assert_called_once()
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
+def test_delete_page_rest_bad_request(
+ transport: str = "rest", request_type=page.DeletePageRequest
):
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_operation(request)
+ client.delete_page(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
+def test_delete_page_rest_flattened():
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ return_value = None
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/pages/sample5"
+ }
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
# Wrap the value into a proper Response obj
response_value = Response()
+ response_value.status_code = 200
json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.list_operations(request)
+ client.delete_page(**mock_args)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/pages/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_page_rest_flattened_error(transport: str = "rest"):
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_page(
+ page.DeletePageRequest(),
+ name="name_value",
+ )
-def test_initialize_client_w_rest():
+def test_delete_page_rest_error():
client = PagesClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_pages_empty_call_rest():
- client = PagesClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.PagesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_pages), "__call__") as call:
- client.list_pages(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.ListPagesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_page_empty_call_rest():
- client = PagesClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.PagesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = PagesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_page), "__call__") as call:
- client.get_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.GetPageRequest()
-
- assert args[0] == request_msg
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.PagesGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = PagesClient(
+ client_options=options,
+ transport=transport,
+ )
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = PagesClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_page_empty_call_rest():
- client = PagesClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.PagesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = PagesClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_page), "__call__") as call:
- client.create_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.CreatePageRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.PagesGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = PagesClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_page_empty_call_rest():
- client = PagesClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.PagesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_page), "__call__") as call:
- client.update_page(request=None)
+ transport = transports.PagesGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_page.UpdatePageRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.PagesGrpcTransport,
+ transports.PagesGrpcAsyncIOTransport,
+ transports.PagesRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_page_empty_call_rest():
- client = PagesClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = PagesClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_page), "__call__") as call:
- client.delete_page(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = page.DeletePageRequest()
-
- assert args[0] == request_msg
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6273,40 +5847,11 @@ def test_parse_page_path():
assert expected == actual
-def test_playbook_path():
- project = "scallop"
- location = "abalone"
- agent = "squid"
- playbook = "clam"
- expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
- project=project,
- location=location,
- agent=agent,
- playbook=playbook,
- )
- actual = PagesClient.playbook_path(project, location, agent, playbook)
- assert expected == actual
-
-
-def test_parse_playbook_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- "agent": "oyster",
- "playbook": "nudibranch",
- }
- path = PagesClient.playbook_path(**expected)
-
- # Check that the path construction is reversible.
- actual = PagesClient.parse_playbook_path(path)
- assert expected == actual
-
-
def test_tool_path():
- project = "cuttlefish"
- location = "mussel"
- agent = "winkle"
- tool = "nautilus"
+ project = "scallop"
+ location = "abalone"
+ agent = "squid"
+ tool = "clam"
expected = (
"projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format(
project=project,
@@ -6321,10 +5866,10 @@ def test_tool_path():
def test_parse_tool_path():
expected = {
- "project": "scallop",
- "location": "abalone",
- "agent": "squid",
- "tool": "clam",
+ "project": "whelk",
+ "location": "octopus",
+ "agent": "oyster",
+ "tool": "nudibranch",
}
path = PagesClient.tool_path(**expected)
@@ -6334,11 +5879,11 @@ def test_parse_tool_path():
def test_transition_route_group_path():
- project = "whelk"
- location = "octopus"
- agent = "oyster"
- flow = "nudibranch"
- transition_route_group = "cuttlefish"
+ project = "cuttlefish"
+ location = "mussel"
+ agent = "winkle"
+ flow = "nautilus"
+ transition_route_group = "scallop"
expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
project=project,
location=location,
@@ -6354,11 +5899,11 @@ def test_transition_route_group_path():
def test_parse_transition_route_group_path():
expected = {
- "project": "mussel",
- "location": "winkle",
- "agent": "nautilus",
- "flow": "scallop",
- "transition_route_group": "abalone",
+ "project": "abalone",
+ "location": "squid",
+ "agent": "clam",
+ "flow": "whelk",
+ "transition_route_group": "octopus",
}
path = PagesClient.transition_route_group_path(**expected)
@@ -6368,10 +5913,10 @@ def test_parse_transition_route_group_path():
def test_webhook_path():
- project = "squid"
- location = "clam"
- agent = "whelk"
- webhook = "octopus"
+ project = "oyster"
+ location = "nudibranch"
+ agent = "cuttlefish"
+ webhook = "mussel"
expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
project=project,
location=location,
@@ -6384,10 +5929,10 @@ def test_webhook_path():
def test_parse_webhook_path():
expected = {
- "project": "oyster",
- "location": "nudibranch",
- "agent": "cuttlefish",
- "webhook": "mussel",
+ "project": "winkle",
+ "location": "nautilus",
+ "agent": "scallop",
+ "webhook": "abalone",
}
path = PagesClient.webhook_path(**expected)
@@ -6397,7 +5942,7 @@ def test_parse_webhook_path():
def test_common_billing_account_path():
- billing_account = "winkle"
+ billing_account = "squid"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -6405,117 +5950,417 @@ def test_common_billing_account_path():
assert expected == actual
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "nautilus",
- }
- path = PagesClient.common_billing_account_path(**expected)
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = PagesClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PagesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = PagesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = PagesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PagesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = PagesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = PagesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PagesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = PagesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = PagesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PagesClient.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 = PagesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = PagesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PagesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep:
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep:
+ transport_class = PagesClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = PagesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = PagesClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = PagesClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = PagesClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = PagesClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = PagesClient.common_organization_path(organization)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = PagesClient.common_organization_path(**expected)
-
- # Check that the path construction is reversible.
- actual = PagesClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = PagesClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = PagesClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = PagesClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = PagesClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = PagesClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = PagesClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep:
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep:
- transport_class = PagesClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6545,7 +6390,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6598,7 +6443,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6643,7 +6488,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6684,7 +6529,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6739,7 +6584,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6786,7 +6631,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6829,7 +6674,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6884,7 +6729,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6931,7 +6776,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -6974,7 +6819,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7029,7 +6874,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7076,7 +6921,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7119,7 +6964,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7171,7 +7016,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = PagesAsyncClient(credentials=async_anonymous_credentials())
+ client = PagesAsyncClient(credentials=ga_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.
@@ -7217,7 +7062,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = PagesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7233,41 +7078,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = PagesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = PagesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = PagesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_playbooks.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_playbooks.py
index 34e1503b029d..734528b26801 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_playbooks.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_playbooks.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,8 +36,16 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.playbooks import (
PlaybooksAsyncClient,
@@ -72,24 +62,10 @@
from google.cloud.dialogflowcx_v3beta1.types import playbook as gcdc_playbook
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1157,6 +1133,25 @@ def test_create_playbook(request_type, transport: str = "grpc"):
assert response.referenced_tools == ["referenced_tools_value"]
+def test_create_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_playbook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_playbook.CreatePlaybookRequest()
+
+
def test_create_playbook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1220,6 +1215,35 @@ def test_create_playbook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_playbook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_playbook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+ )
+ response = await client.create_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_playbook.CreatePlaybookRequest()
+
+
@pytest.mark.asyncio
async def test_create_playbook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1228,7 +1252,7 @@ async def test_create_playbook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1243,23 +1267,27 @@ async def test_create_playbook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_playbook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_playbook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_playbook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1267,7 +1295,7 @@ async def test_create_playbook_async(
transport: str = "grpc_asyncio", request_type=gcdc_playbook.CreatePlaybookRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1345,7 +1373,7 @@ def test_create_playbook_field_headers():
@pytest.mark.asyncio
async def test_create_playbook_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1420,7 +1448,7 @@ def test_create_playbook_flattened_error():
@pytest.mark.asyncio
async def test_create_playbook_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1453,7 +1481,7 @@ async def test_create_playbook_flattened_async():
@pytest.mark.asyncio
async def test_create_playbook_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1499,6 +1527,25 @@ def test_delete_playbook(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.DeletePlaybookRequest()
+
+
def test_delete_playbook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1562,6 +1609,25 @@ def test_delete_playbook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_playbook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.DeletePlaybookRequest()
+
+
@pytest.mark.asyncio
async def test_delete_playbook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1570,7 +1636,7 @@ async def test_delete_playbook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1585,23 +1651,27 @@ async def test_delete_playbook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_playbook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_playbook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_playbook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1609,7 +1679,7 @@ async def test_delete_playbook_async(
transport: str = "grpc_asyncio", request_type=playbook.DeletePlaybookRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1670,7 +1740,7 @@ def test_delete_playbook_field_headers():
@pytest.mark.asyncio
async def test_delete_playbook_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1738,7 +1808,7 @@ def test_delete_playbook_flattened_error():
@pytest.mark.asyncio
async def test_delete_playbook_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1765,7 +1835,7 @@ async def test_delete_playbook_flattened_async():
@pytest.mark.asyncio
async def test_delete_playbook_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1813,6 +1883,25 @@ def test_list_playbooks(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_playbooks_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_playbooks()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.ListPlaybooksRequest()
+
+
def test_list_playbooks_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1878,6 +1967,29 @@ def test_list_playbooks_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_playbooks_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ playbook.ListPlaybooksResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_playbooks()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.ListPlaybooksRequest()
+
+
@pytest.mark.asyncio
async def test_list_playbooks_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1886,7 +1998,7 @@ async def test_list_playbooks_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1901,23 +2013,27 @@ async def test_list_playbooks_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_playbooks
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_playbooks(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_playbooks(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1925,7 +2041,7 @@ async def test_list_playbooks_async(
transport: str = "grpc_asyncio", request_type=playbook.ListPlaybooksRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1991,7 +2107,7 @@ def test_list_playbooks_field_headers():
@pytest.mark.asyncio
async def test_list_playbooks_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2061,7 +2177,7 @@ def test_list_playbooks_flattened_error():
@pytest.mark.asyncio
async def test_list_playbooks_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2090,7 +2206,7 @@ async def test_list_playbooks_flattened_async():
@pytest.mark.asyncio
async def test_list_playbooks_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2140,16 +2256,12 @@ def test_list_playbooks_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_playbooks(request={}, retry=retry, timeout=timeout)
+ pager = client.list_playbooks(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -2200,7 +2312,7 @@ def test_list_playbooks_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_playbooks_async_pager():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2250,7 +2362,7 @@ async def test_list_playbooks_async_pager():
@pytest.mark.asyncio
async def test_list_playbooks_async_pages():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2344,6 +2456,25 @@ def test_get_playbook(request_type, transport: str = "grpc"):
assert response.referenced_tools == ["referenced_tools_value"]
+def test_get_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_playbook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.GetPlaybookRequest()
+
+
def test_get_playbook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2407,6 +2538,35 @@ def test_get_playbook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_playbook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_playbook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+ )
+ response = await client.get_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.GetPlaybookRequest()
+
+
@pytest.mark.asyncio
async def test_get_playbook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2415,7 +2575,7 @@ async def test_get_playbook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2430,23 +2590,27 @@ async def test_get_playbook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_playbook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_playbook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_playbook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2454,7 +2618,7 @@ async def test_get_playbook_async(
transport: str = "grpc_asyncio", request_type=playbook.GetPlaybookRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2532,7 +2696,7 @@ def test_get_playbook_field_headers():
@pytest.mark.asyncio
async def test_get_playbook_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2600,7 +2764,7 @@ def test_get_playbook_flattened_error():
@pytest.mark.asyncio
async def test_get_playbook_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2627,7 +2791,7 @@ async def test_get_playbook_flattened_async():
@pytest.mark.asyncio
async def test_get_playbook_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2687,6 +2851,25 @@ def test_update_playbook(request_type, transport: str = "grpc"):
assert response.referenced_tools == ["referenced_tools_value"]
+def test_update_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_playbook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_playbook.UpdatePlaybookRequest()
+
+
def test_update_playbook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2746,6 +2929,35 @@ def test_update_playbook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_playbook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_playbook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+ )
+ response = await client.update_playbook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_playbook.UpdatePlaybookRequest()
+
+
@pytest.mark.asyncio
async def test_update_playbook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2754,7 +2966,7 @@ async def test_update_playbook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2769,23 +2981,27 @@ async def test_update_playbook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_playbook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_playbook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_playbook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2793,7 +3009,7 @@ async def test_update_playbook_async(
transport: str = "grpc_asyncio", request_type=gcdc_playbook.UpdatePlaybookRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2871,7 +3087,7 @@ def test_update_playbook_field_headers():
@pytest.mark.asyncio
async def test_update_playbook_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2946,7 +3162,7 @@ def test_update_playbook_flattened_error():
@pytest.mark.asyncio
async def test_update_playbook_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2979,7 +3195,7 @@ async def test_update_playbook_flattened_async():
@pytest.mark.asyncio
async def test_update_playbook_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3032,19 +3248,40 @@ def test_create_playbook_version(request_type, transport: str = "grpc"):
assert response.description == "description_value"
-def test_create_playbook_version_non_empty_request_with_auto_populated_field():
- # This test is a coverage failsafe to make sure that UUID4 fields are
- # automatically populated, according to AIP-4235, with non-empty requests.
+def test_create_playbook_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 = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
- # Populate all string fields in the request which are not UUID4
- # since we want to check that UUID4 are populated automatically
- # if they meet the requirements of AIP 4235.
- request = playbook.CreatePlaybookVersionRequest(
- parent="parent_value",
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_playbook_version), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.CreatePlaybookVersionRequest()
+
+
+def test_create_playbook_version_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = playbook.CreatePlaybookVersionRequest(
+ parent="parent_value",
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3102,6 +3339,32 @@ def test_create_playbook_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_playbook_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_playbook_version), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ playbook.PlaybookVersion(
+ name="name_value",
+ description="description_value",
+ )
+ )
+ response = await client.create_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.CreatePlaybookVersionRequest()
+
+
@pytest.mark.asyncio
async def test_create_playbook_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3110,7 +3373,7 @@ async def test_create_playbook_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3125,23 +3388,27 @@ async def test_create_playbook_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_playbook_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_playbook_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_playbook_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3149,7 +3416,7 @@ async def test_create_playbook_version_async(
transport: str = "grpc_asyncio", request_type=playbook.CreatePlaybookVersionRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3221,7 +3488,7 @@ def test_create_playbook_version_field_headers():
@pytest.mark.asyncio
async def test_create_playbook_version_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3300,7 +3567,7 @@ def test_create_playbook_version_flattened_error():
@pytest.mark.asyncio
async def test_create_playbook_version_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3335,7 +3602,7 @@ async def test_create_playbook_version_flattened_async():
@pytest.mark.asyncio
async def test_create_playbook_version_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3388,6 +3655,27 @@ def test_get_playbook_version(request_type, transport: str = "grpc"):
assert response.description == "description_value"
+def test_get_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_playbook_version), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.GetPlaybookVersionRequest()
+
+
def test_get_playbook_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3457,6 +3745,32 @@ def test_get_playbook_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_playbook_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_playbook_version), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ playbook.PlaybookVersion(
+ name="name_value",
+ description="description_value",
+ )
+ )
+ response = await client.get_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.GetPlaybookVersionRequest()
+
+
@pytest.mark.asyncio
async def test_get_playbook_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3465,7 +3779,7 @@ async def test_get_playbook_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3480,23 +3794,27 @@ async def test_get_playbook_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_playbook_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_playbook_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_playbook_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3504,7 +3822,7 @@ async def test_get_playbook_version_async(
transport: str = "grpc_asyncio", request_type=playbook.GetPlaybookVersionRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3576,7 +3894,7 @@ def test_get_playbook_version_field_headers():
@pytest.mark.asyncio
async def test_get_playbook_version_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3650,7 +3968,7 @@ def test_get_playbook_version_flattened_error():
@pytest.mark.asyncio
async def test_get_playbook_version_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3681,7 +3999,7 @@ async def test_get_playbook_version_flattened_async():
@pytest.mark.asyncio
async def test_get_playbook_version_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3731,6 +4049,27 @@ def test_list_playbook_versions(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_playbook_versions), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_playbook_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.ListPlaybookVersionsRequest()
+
+
def test_list_playbook_versions_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3803,6 +4142,31 @@ def test_list_playbook_versions_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_playbook_versions_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_playbook_versions), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ playbook.ListPlaybookVersionsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_playbook_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.ListPlaybookVersionsRequest()
+
+
@pytest.mark.asyncio
async def test_list_playbook_versions_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3811,7 +4175,7 @@ async def test_list_playbook_versions_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3826,23 +4190,27 @@ async def test_list_playbook_versions_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_playbook_versions
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_playbook_versions(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_playbook_versions(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3850,7 +4218,7 @@ async def test_list_playbook_versions_async(
transport: str = "grpc_asyncio", request_type=playbook.ListPlaybookVersionsRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3920,7 +4288,7 @@ def test_list_playbook_versions_field_headers():
@pytest.mark.asyncio
async def test_list_playbook_versions_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3994,7 +4362,7 @@ def test_list_playbook_versions_flattened_error():
@pytest.mark.asyncio
async def test_list_playbook_versions_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4025,7 +4393,7 @@ async def test_list_playbook_versions_flattened_async():
@pytest.mark.asyncio
async def test_list_playbook_versions_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4077,16 +4445,12 @@ def test_list_playbook_versions_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_playbook_versions(request={}, retry=retry, timeout=timeout)
+ pager = client.list_playbook_versions(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -4139,7 +4503,7 @@ def test_list_playbook_versions_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_playbook_versions_async_pager():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4191,7 +4555,7 @@ async def test_list_playbook_versions_async_pager():
@pytest.mark.asyncio
async def test_list_playbook_versions_async_pages():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4274,6 +4638,27 @@ def test_delete_playbook_version(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_playbook_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 = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_playbook_version), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.DeletePlaybookVersionRequest()
+
+
def test_delete_playbook_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4344,6 +4729,27 @@ def test_delete_playbook_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_playbook_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_playbook_version), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_playbook_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == playbook.DeletePlaybookVersionRequest()
+
+
@pytest.mark.asyncio
async def test_delete_playbook_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4352,7 +4758,7 @@ async def test_delete_playbook_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4367,23 +4773,27 @@ async def test_delete_playbook_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_playbook_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_playbook_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_playbook_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4391,7 +4801,7 @@ async def test_delete_playbook_version_async(
transport: str = "grpc_asyncio", request_type=playbook.DeletePlaybookVersionRequest
):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4456,7 +4866,7 @@ def test_delete_playbook_version_field_headers():
@pytest.mark.asyncio
async def test_delete_playbook_version_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4528,7 +4938,7 @@ def test_delete_playbook_version_flattened_error():
@pytest.mark.asyncio
async def test_delete_playbook_version_flattened_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4557,7 +4967,7 @@ async def test_delete_playbook_version_flattened_async():
@pytest.mark.asyncio
async def test_delete_playbook_version_flattened_error_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4569,31 +4979,173 @@ async def test_delete_playbook_version_flattened_error_async():
)
-def test_create_playbook_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_playbook.CreatePlaybookRequest,
+ dict,
+ ],
+)
+def test_create_playbook_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Ensure method has been cached
- assert client._transport.create_playbook in client._transport._wrapped_methods
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["playbook"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "goal": "goal_value",
+ "input_parameter_definitions": [
+ {"name": "name_value", "type_": 1, "description": "description_value"}
+ ],
+ "output_parameter_definitions": {},
+ "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
+ "token_count": 1193,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "referenced_playbooks": [
+ "referenced_playbooks_value1",
+ "referenced_playbooks_value2",
+ ],
+ "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
+ "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
+ "llm_model_settings": {
+ "model": "model_value",
+ "prompt_text": "prompt_text_value",
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.create_playbook] = mock_rpc
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_playbook.CreatePlaybookRequest.meta.fields["playbook"]
- request = {}
- client.create_playbook(request)
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["playbook"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["playbook"][field])):
+ del request_init["playbook"][field][i][subfield]
+ else:
+ del request_init["playbook"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_playbook.Playbook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_playbook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_playbook.Playbook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.goal == "goal_value"
+ assert response.token_count == 1193
+ assert response.referenced_playbooks == ["referenced_playbooks_value"]
+ assert response.referenced_flows == ["referenced_flows_value"]
+ assert response.referenced_tools == ["referenced_tools_value"]
+
+
+def test_create_playbook_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_playbook in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_playbook] = mock_rpc
+
+ request = {}
+ client.create_playbook(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
@@ -4697,6 +5249,85 @@ def test_create_playbook_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_playbook_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ )
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_create_playbook"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_create_playbook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_playbook.CreatePlaybookRequest.pb(
+ gcdc_playbook.CreatePlaybookRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_playbook.Playbook.to_json(
+ gcdc_playbook.Playbook()
+ )
+
+ request = gcdc_playbook.CreatePlaybookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_playbook.Playbook()
+
+ client.create_playbook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_playbook_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_playbook.CreatePlaybookRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_playbook(request)
+
+
def test_create_playbook_rest_flattened():
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4756,6 +5387,49 @@ def test_create_playbook_rest_flattened_error(transport: str = "rest"):
)
+def test_create_playbook_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.DeletePlaybookRequest,
+ dict,
+ ],
+)
+def test_delete_playbook_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_playbook(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_playbook_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4872,10 +5546,81 @@ def test_delete_playbook_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_delete_playbook_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_playbook_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ )
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_delete_playbook"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = playbook.DeletePlaybookRequest.pb(playbook.DeletePlaybookRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = playbook.DeletePlaybookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_playbook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_playbook_rest_bad_request(
+ transport: str = "rest", request_type=playbook.DeletePlaybookRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_playbook(request)
+
+
+def test_delete_playbook_rest_flattened():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# Mock the http request call within the method and fake a response.
@@ -4929,6 +5674,52 @@ def test_delete_playbook_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_playbook_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.ListPlaybooksRequest,
+ dict,
+ ],
+)
+def test_list_playbooks_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.ListPlaybooksResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.ListPlaybooksResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_playbooks(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListPlaybooksPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_playbooks_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5063,6 +5854,83 @@ def test_list_playbooks_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_playbooks_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ )
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_list_playbooks"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_list_playbooks"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = playbook.ListPlaybooksRequest.pb(playbook.ListPlaybooksRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = playbook.ListPlaybooksResponse.to_json(
+ playbook.ListPlaybooksResponse()
+ )
+
+ request = playbook.ListPlaybooksRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = playbook.ListPlaybooksResponse()
+
+ client.list_playbooks(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_playbooks_rest_bad_request(
+ transport: str = "rest", request_type=playbook.ListPlaybooksRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_playbooks(request)
+
+
def test_list_playbooks_rest_flattened():
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5181,6 +6049,60 @@ def test_list_playbooks_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.GetPlaybookRequest,
+ dict,
+ ],
+)
+def test_get_playbook_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.Playbook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_playbook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, playbook.Playbook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.goal == "goal_value"
+ assert response.token_count == 1193
+ assert response.referenced_playbooks == ["referenced_playbooks_value"]
+ assert response.referenced_flows == ["referenced_flows_value"]
+ assert response.referenced_tools == ["referenced_tools_value"]
+
+
def test_get_playbook_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5298,25 +6220,102 @@ def test_get_playbook_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_get_playbook_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_playbook_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.Playbook()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_get_playbook"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_get_playbook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = playbook.GetPlaybookRequest.pb(playbook.GetPlaybookRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = playbook.Playbook.to_json(playbook.Playbook())
+
+ request = playbook.GetPlaybookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = playbook.Playbook()
+
+ client.get_playbook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_playbook_rest_bad_request(
+ transport: str = "rest", request_type=playbook.GetPlaybookRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_playbook(request)
+
+
+def test_get_playbook_rest_flattened():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.Playbook()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
)
mock_args.update(sample_request)
@@ -5357,6 +6356,158 @@ def test_get_playbook_rest_flattened_error(transport: str = "rest"):
)
+def test_get_playbook_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_playbook.UpdatePlaybookRequest,
+ dict,
+ ],
+)
+def test_update_playbook_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "playbook": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ }
+ request_init["playbook"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4",
+ "display_name": "display_name_value",
+ "goal": "goal_value",
+ "input_parameter_definitions": [
+ {"name": "name_value", "type_": 1, "description": "description_value"}
+ ],
+ "output_parameter_definitions": {},
+ "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
+ "token_count": 1193,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "referenced_playbooks": [
+ "referenced_playbooks_value1",
+ "referenced_playbooks_value2",
+ ],
+ "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
+ "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
+ "llm_model_settings": {
+ "model": "model_value",
+ "prompt_text": "prompt_text_value",
+ },
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_playbook.UpdatePlaybookRequest.meta.fields["playbook"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["playbook"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["playbook"][field])):
+ del request_init["playbook"][field][i][subfield]
+ else:
+ del request_init["playbook"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_playbook.Playbook(
+ name="name_value",
+ display_name="display_name_value",
+ goal="goal_value",
+ token_count=1193,
+ referenced_playbooks=["referenced_playbooks_value"],
+ referenced_flows=["referenced_flows_value"],
+ referenced_tools=["referenced_tools_value"],
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_playbook.Playbook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_playbook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_playbook.Playbook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.goal == "goal_value"
+ assert response.token_count == 1193
+ assert response.referenced_playbooks == ["referenced_playbooks_value"]
+ assert response.referenced_flows == ["referenced_flows_value"]
+ assert response.referenced_tools == ["referenced_tools_value"]
+
+
def test_update_playbook_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5474,203 +6625,90 @@ def test_update_playbook_rest_unset_required_fields():
assert set(unset_fields) == (set(("updateMask",)) & set(("playbook",)))
-def test_update_playbook_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_playbook_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_playbook.Playbook()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "playbook": {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_update_playbook"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_update_playbook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_playbook.UpdatePlaybookRequest.pb(
+ gcdc_playbook.UpdatePlaybookRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- playbook=gcdc_playbook.Playbook(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_playbook.Playbook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_playbook(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{playbook.name=projects/*/locations/*/agents/*/playbooks/*}"
- % client.transport._host,
- args[1],
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_playbook.Playbook.to_json(
+ gcdc_playbook.Playbook()
)
+ request = gcdc_playbook.UpdatePlaybookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_playbook.Playbook()
-def test_update_playbook_rest_flattened_error(transport: str = "rest"):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
client.update_playbook(
- gcdc_playbook.UpdatePlaybookRequest(),
- playbook=gcdc_playbook.Playbook(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_create_playbook_version_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.create_playbook_version
- in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[
- client._transport.create_playbook_version
- ] = mock_rpc
-
- request = {}
- client.create_playbook_version(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
- client.create_playbook_version(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_create_playbook_version_rest_required_fields(
- request_type=playbook.CreatePlaybookVersionRequest,
+def test_update_playbook_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_playbook.UpdatePlaybookRequest
):
- transport_class = transports.PlaybooksRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_playbook_version._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_playbook_version._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = playbook.PlaybookVersion()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.PlaybookVersion.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.create_playbook_version(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
+ # send a request that will satisfy transcoding
+ request_init = {
+ "playbook": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ }
+ request = request_type(**request_init)
-def test_create_playbook_version_rest_unset_required_fields():
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_playbook_version._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "parent",
- "playbookVersion",
- )
- )
- )
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_playbook(request)
-def test_create_playbook_version_rest_flattened():
+def test_update_playbook_rest_flattened():
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -5679,17 +6717,19 @@ def test_create_playbook_version_rest_flattened():
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = playbook.PlaybookVersion()
+ return_value = gcdc_playbook.Playbook()
# get arguments that satisfy an http rule for this method
sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ "playbook": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
}
# get truthy value for each flattened field
mock_args = dict(
- parent="parent_value",
- playbook_version=playbook.PlaybookVersion(name="name_value"),
+ playbook=gcdc_playbook.Playbook(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
@@ -5697,25 +6737,25 @@ def test_create_playbook_version_rest_flattened():
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = playbook.PlaybookVersion.pb(return_value)
+ return_value = gcdc_playbook.Playbook.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.create_playbook_version(**mock_args)
+ client.update_playbook(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions"
+ "%s/v3beta1/{playbook.name=projects/*/locations/*/agents/*/playbooks/*}"
% client.transport._host,
args[1],
)
-def test_create_playbook_version_rest_flattened_error(transport: str = "rest"):
+def test_update_playbook_rest_flattened_error(transport: str = "rest"):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5724,60 +6764,250 @@ def test_create_playbook_version_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.create_playbook_version(
- playbook.CreatePlaybookVersionRequest(),
- parent="parent_value",
- playbook_version=playbook.PlaybookVersion(name="name_value"),
+ client.update_playbook(
+ gcdc_playbook.UpdatePlaybookRequest(),
+ playbook=gcdc_playbook.Playbook(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
-def test_get_playbook_version_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_update_playbook_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
- # Ensure method has been cached
- assert (
- client._transport.get_playbook_version in client._transport._wrapped_methods
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.CreatePlaybookVersionRequest,
+ dict,
+ ],
+)
+def test_create_playbook_version_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request_init["playbook_version"] = {
+ "name": "name_value",
+ "description": "description_value",
+ "playbook": {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "goal": "goal_value",
+ "input_parameter_definitions": [
+ {"name": "name_value", "type_": 1, "description": "description_value"}
+ ],
+ "output_parameter_definitions": {},
+ "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
+ "token_count": 1193,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "referenced_playbooks": [
+ "referenced_playbooks_value1",
+ "referenced_playbooks_value2",
+ ],
+ "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
+ "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
+ "llm_model_settings": {
+ "model": "model_value",
+ "prompt_text": "prompt_text_value",
+ },
+ },
+ "examples": [
+ {
+ "name": "name_value",
+ "playbook_input": {
+ "preceding_conversation_summary": "preceding_conversation_summary_value",
+ "action_parameters": {"fields": {}},
+ },
+ "playbook_output": {
+ "execution_summary": "execution_summary_value",
+ "action_parameters": {},
+ },
+ "actions": [
+ {
+ "user_utterance": {"text": "text_value"},
+ "agent_utterance": {"text": "text_value"},
+ "tool_use": {
+ "tool": "tool_value",
+ "action": "action_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ },
+ "playbook_invocation": {
+ "playbook": "playbook_value",
+ "playbook_input": {},
+ "playbook_output": {},
+ "playbook_state": 1,
+ },
+ "flow_invocation": {
+ "flow": "flow_value",
+ "input_action_parameters": {},
+ "output_action_parameters": {},
+ "flow_state": 1,
+ },
+ }
+ ],
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "token_count": 1193,
+ "create_time": {},
+ "update_time": {},
+ "conversation_state": 1,
+ "language_code": "language_code_value",
+ }
+ ],
+ "update_time": {},
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = playbook.CreatePlaybookVersionRequest.meta.fields["playbook_version"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["playbook_version"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["playbook_version"][field])):
+ del request_init["playbook_version"][field][i][subfield]
+ else:
+ del request_init["playbook_version"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.PlaybookVersion(
+ name="name_value",
+ description="description_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.PlaybookVersion.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_playbook_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, playbook.PlaybookVersion)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+
+
+def test_create_playbook_version_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.create_playbook_version
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
client._transport._wrapped_methods[
- client._transport.get_playbook_version
+ client._transport.create_playbook_version
] = mock_rpc
request = {}
- client.get_playbook_version(request)
+ client.create_playbook_version(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.get_playbook_version(request)
+ client.create_playbook_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_get_playbook_version_rest_required_fields(
- request_type=playbook.GetPlaybookVersionRequest,
+def test_create_playbook_version_rest_required_fields(
+ request_type=playbook.CreatePlaybookVersionRequest,
):
transport_class = transports.PlaybooksRestTransport
request_init = {}
- request_init["name"] = ""
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5788,21 +7018,21 @@ def test_get_playbook_version_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).get_playbook_version._get_unset_required_fields(jsonified_request)
+ ).create_playbook_version._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
+ jsonified_request["parent"] = "parent_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).get_playbook_version._get_unset_required_fields(jsonified_request)
+ ).create_playbook_version._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5823,9 +7053,10 @@ def test_get_playbook_version_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "get",
+ "method": "post",
"query_params": pb_request,
}
+ transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
@@ -5838,41 +7069,131 @@ def test_get_playbook_version_rest_required_fields(
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_playbook_version(request)
+ response = client.create_playbook_version(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_get_playbook_version_rest_unset_required_fields():
+def test_create_playbook_version_rest_unset_required_fields():
transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.get_playbook_version._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ unset_fields = transport.create_playbook_version._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(())
+ & set(
+ (
+ "parent",
+ "playbookVersion",
+ )
+ )
+ )
-def test_get_playbook_version_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_playbook_version_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.PlaybookVersion()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_create_playbook_version"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_create_playbook_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = playbook.CreatePlaybookVersionRequest.pb(
+ playbook.CreatePlaybookVersionRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = playbook.PlaybookVersion.to_json(
+ playbook.PlaybookVersion()
+ )
+
+ request = playbook.CreatePlaybookVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = playbook.PlaybookVersion()
+
+ client.create_playbook_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_playbook_version_rest_bad_request(
+ transport: str = "rest", request_type=playbook.CreatePlaybookVersionRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_playbook_version(request)
+
+
+def test_create_playbook_version_rest_flattened():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.PlaybookVersion()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ playbook_version=playbook.PlaybookVersion(name="name_value"),
)
mock_args.update(sample_request)
@@ -5885,20 +7206,20 @@ def test_get_playbook_version_rest_flattened():
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.get_playbook_version(**mock_args)
+ client.create_playbook_version(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}"
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions"
% client.transport._host,
args[1],
)
-def test_get_playbook_version_rest_flattened_error(transport: str = "rest"):
+def test_create_playbook_version_rest_flattened_error(transport: str = "rest"):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5907,13 +7228,64 @@ def test_get_playbook_version_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.get_playbook_version(
- playbook.GetPlaybookVersionRequest(),
+ client.create_playbook_version(
+ playbook.CreatePlaybookVersionRequest(),
+ parent="parent_value",
+ playbook_version=playbook.PlaybookVersion(name="name_value"),
+ )
+
+
+def test_create_playbook_version_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.GetPlaybookVersionRequest,
+ dict,
+ ],
+)
+def test_get_playbook_version_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.PlaybookVersion(
name="name_value",
+ description="description_value",
)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.PlaybookVersion.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
-def test_list_playbook_versions_rest_use_cached_wrapped_rpc():
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_playbook_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, playbook.PlaybookVersion)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+
+
+def test_get_playbook_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -5928,8 +7300,7 @@ def test_list_playbook_versions_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.list_playbook_versions
- in client._transport._wrapped_methods
+ client._transport.get_playbook_version in client._transport._wrapped_methods
)
# Replace cached wrapped function with mock
@@ -5938,29 +7309,29 @@ def test_list_playbook_versions_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.list_playbook_versions
+ client._transport.get_playbook_version
] = mock_rpc
request = {}
- client.list_playbook_versions(request)
+ client.get_playbook_version(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.list_playbook_versions(request)
+ client.get_playbook_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_list_playbook_versions_rest_required_fields(
- request_type=playbook.ListPlaybookVersionsRequest,
+def test_get_playbook_version_rest_required_fields(
+ request_type=playbook.GetPlaybookVersionRequest,
):
transport_class = transports.PlaybooksRestTransport
request_init = {}
- request_init["parent"] = ""
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -5971,28 +7342,21 @@ def test_list_playbook_versions_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).list_playbook_versions._get_unset_required_fields(jsonified_request)
+ ).get_playbook_version._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["parent"] = "parent_value"
+ jsonified_request["name"] = "name_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).list_playbook_versions._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "page_size",
- "page_token",
- )
- )
+ ).get_playbook_version._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6001,7 +7365,7 @@ def test_list_playbook_versions_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = playbook.ListPlaybookVersionsResponse()
+ return_value = playbook.PlaybookVersion()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6022,81 +7386,154 @@ def test_list_playbook_versions_rest_required_fields(
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
+ return_value = playbook.PlaybookVersion.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_playbook_versions(request)
+ response = client.get_playbook_version(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_list_playbook_versions_rest_unset_required_fields():
+def test_get_playbook_version_rest_unset_required_fields():
transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.list_playbook_versions._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "pageSize",
- "pageToken",
- )
- )
- & set(("parent",))
- )
+ unset_fields = transport.get_playbook_version._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-def test_list_playbook_versions_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_playbook_version_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.ListPlaybookVersionsResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "post_get_playbook_version"
+ ) as post, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_get_playbook_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = playbook.GetPlaybookVersionRequest.pb(
+ playbook.GetPlaybookVersionRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = playbook.PlaybookVersion.to_json(
+ playbook.PlaybookVersion()
)
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- client.list_playbook_versions(**mock_args)
+ request = playbook.GetPlaybookVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = playbook.PlaybookVersion()
+
+ client.get_playbook_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_playbook_version_rest_bad_request(
+ transport: str = "rest", request_type=playbook.GetPlaybookVersionRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_playbook_version(request)
+
+
+def test_get_playbook_version_rest_flattened():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.PlaybookVersion()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.PlaybookVersion.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.get_playbook_version(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions"
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}"
% client.transport._host,
args[1],
)
-def test_list_playbook_versions_rest_flattened_error(transport: str = "rest"):
+def test_get_playbook_version_rest_flattened_error(transport: str = "rest"):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -6105,78 +7542,61 @@ def test_list_playbook_versions_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.list_playbook_versions(
- playbook.ListPlaybookVersionsRequest(),
- parent="parent_value",
+ client.get_playbook_version(
+ playbook.GetPlaybookVersionRequest(),
+ name="name_value",
)
-def test_list_playbook_versions_rest_pager(transport: str = "rest"):
+def test_get_playbook_version_rest_error():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ playbook.ListPlaybookVersionsRequest,
+ dict,
+ ],
+)
+def test_list_playbook_versions_rest(request_type):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="rest",
)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- playbook.ListPlaybookVersionsResponse(
- playbook_versions=[
- playbook.PlaybookVersion(),
- playbook.PlaybookVersion(),
- playbook.PlaybookVersion(),
- ],
- next_page_token="abc",
- ),
- playbook.ListPlaybookVersionsResponse(
- playbook_versions=[],
- next_page_token="def",
- ),
- playbook.ListPlaybookVersionsResponse(
- playbook_versions=[
- playbook.PlaybookVersion(),
- ],
- next_page_token="ghi",
- ),
- playbook.ListPlaybookVersionsResponse(
- playbook_versions=[
- playbook.PlaybookVersion(),
- playbook.PlaybookVersion(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+ request = request_type(**request_init)
- # Wrap the values into proper Response objs
- response = tuple(
- playbook.ListPlaybookVersionsResponse.to_json(x) for x in response
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = playbook.ListPlaybookVersionsResponse(
+ next_page_token="next_page_token_value",
)
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- pager = client.list_playbook_versions(request=sample_request)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, playbook.PlaybookVersion) for i in results)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_playbook_versions(request)
- pages = list(client.list_playbook_versions(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListPlaybookVersionsPager)
+ assert response.next_page_token == "next_page_token_value"
-def test_delete_playbook_version_rest_use_cached_wrapped_rpc():
+def test_list_playbook_versions_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -6191,7 +7611,7 @@ def test_delete_playbook_version_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.delete_playbook_version
+ client._transport.list_playbook_versions
in client._transport._wrapped_methods
)
@@ -6201,29 +7621,29 @@ def test_delete_playbook_version_rest_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.delete_playbook_version
+ client._transport.list_playbook_versions
] = mock_rpc
request = {}
- client.delete_playbook_version(request)
+ client.list_playbook_versions(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.delete_playbook_version(request)
+ client.list_playbook_versions(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_delete_playbook_version_rest_required_fields(
- request_type=playbook.DeletePlaybookVersionRequest,
+def test_list_playbook_versions_rest_required_fields(
+ request_type=playbook.ListPlaybookVersionsRequest,
):
transport_class = transports.PlaybooksRestTransport
request_init = {}
- request_init["name"] = ""
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -6234,21 +7654,28 @@ def test_delete_playbook_version_rest_required_fields(
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_playbook_version._get_unset_required_fields(jsonified_request)
+ ).list_playbook_versions._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
+ jsonified_request["parent"] = "parent_value"
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_playbook_version._get_unset_required_fields(jsonified_request)
+ ).list_playbook_versions._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "page_size",
+ "page_token",
+ )
+ )
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -6257,7 +7684,7 @@ def test_delete_playbook_version_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = playbook.ListPlaybookVersionsResponse()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -6269,1932 +7696,52 @@ def test_delete_playbook_version_rest_required_fields(
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "delete",
+ "method": "get",
"query_params": pb_request,
}
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+
+ # Convert return value to protobuf type
+ return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_playbook_version(request)
+ response = client.list_playbook_versions(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_delete_playbook_version_rest_unset_required_fields():
+def test_list_playbook_versions_rest_unset_required_fields():
transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.delete_playbook_version._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
+ unset_fields = transport.list_playbook_versions._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "pageSize",
+ "pageToken",
+ )
+ )
+ & set(("parent",))
+ )
-def test_delete_playbook_version_rest_flattened():
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_playbook_versions_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_playbook_version(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_playbook_version_rest_flattened_error(transport: str = "rest"):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_playbook_version(
- playbook.DeletePlaybookVersionRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PlaybooksClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = PlaybooksClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = PlaybooksClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = PlaybooksClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = PlaybooksClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.PlaybooksGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.PlaybooksGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.PlaybooksGrpcTransport,
- transports.PlaybooksGrpcAsyncIOTransport,
- transports.PlaybooksRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = PlaybooksClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_playbook_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_playbook), "__call__") as call:
- call.return_value = gcdc_playbook.Playbook()
- client.create_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.CreatePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_playbook_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call:
- call.return_value = None
- client.delete_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_playbooks_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call:
- call.return_value = playbook.ListPlaybooksResponse()
- client.list_playbooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_playbook_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_playbook), "__call__") as call:
- call.return_value = playbook.Playbook()
- client.get_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_playbook_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_playbook), "__call__") as call:
- call.return_value = gcdc_playbook.Playbook()
- client.update_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.UpdatePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_playbook_version_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_playbook_version), "__call__"
- ) as call:
- call.return_value = playbook.PlaybookVersion()
- client.create_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.CreatePlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_playbook_version_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_playbook_version), "__call__"
- ) as call:
- call.return_value = playbook.PlaybookVersion()
- client.get_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_playbook_versions_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_playbook_versions), "__call__"
- ) as call:
- call.return_value = playbook.ListPlaybookVersionsResponse()
- client.list_playbook_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybookVersionsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_playbook_version_empty_call_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_playbook_version), "__call__"
- ) as call:
- call.return_value = None
- client.delete_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = PlaybooksAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_playbook_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_playbook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
- )
- await client.create_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.CreatePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_playbook_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_playbooks_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- playbook.ListPlaybooksResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_playbooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_playbook_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_playbook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
- )
- await client.get_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_playbook_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_playbook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
- )
- await client.update_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.UpdatePlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_playbook_version_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_playbook_version), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- playbook.PlaybookVersion(
- name="name_value",
- description="description_value",
- )
- )
- await client.create_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.CreatePlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_playbook_version_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_playbook_version), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- playbook.PlaybookVersion(
- name="name_value",
- description="description_value",
- )
- )
- await client.get_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_playbook_versions_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_playbook_versions), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- playbook.ListPlaybookVersionsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_playbook_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybookVersionsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_playbook_version_empty_call_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_playbook_version), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookVersionRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = PlaybooksClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_create_playbook_rest_bad_request(
- request_type=gcdc_playbook.CreatePlaybookRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_playbook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_playbook.CreatePlaybookRequest,
- dict,
- ],
-)
-def test_create_playbook_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["playbook"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "goal": "goal_value",
- "input_parameter_definitions": [
- {"name": "name_value", "type_": 1, "description": "description_value"}
- ],
- "output_parameter_definitions": {},
- "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
- "token_count": 1193,
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "referenced_playbooks": [
- "referenced_playbooks_value1",
- "referenced_playbooks_value2",
- ],
- "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
- "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
- "llm_model_settings": {
- "model": "model_value",
- "prompt_text": "prompt_text_value",
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_playbook.CreatePlaybookRequest.meta.fields["playbook"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["playbook"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["playbook"][field])):
- del request_init["playbook"][field][i][subfield]
- else:
- del request_init["playbook"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_playbook.Playbook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_playbook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_playbook.Playbook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.goal == "goal_value"
- assert response.token_count == 1193
- assert response.referenced_playbooks == ["referenced_playbooks_value"]
- assert response.referenced_flows == ["referenced_flows_value"]
- assert response.referenced_tools == ["referenced_tools_value"]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_playbook_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_create_playbook"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_create_playbook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_playbook.CreatePlaybookRequest.pb(
- gcdc_playbook.CreatePlaybookRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_playbook.Playbook.to_json(gcdc_playbook.Playbook())
- req.return_value.content = return_value
-
- request = gcdc_playbook.CreatePlaybookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_playbook.Playbook()
-
- client.create_playbook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_playbook_rest_bad_request(request_type=playbook.DeletePlaybookRequest):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_playbook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.DeletePlaybookRequest,
- dict,
- ],
-)
-def test_delete_playbook_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_playbook(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_playbook_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_delete_playbook"
- ) as pre:
- pre.assert_not_called()
- pb_message = playbook.DeletePlaybookRequest.pb(playbook.DeletePlaybookRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = playbook.DeletePlaybookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_playbook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_list_playbooks_rest_bad_request(request_type=playbook.ListPlaybooksRequest):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_playbooks(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.ListPlaybooksRequest,
- dict,
- ],
-)
-def test_list_playbooks_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.ListPlaybooksResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.ListPlaybooksResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_playbooks(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListPlaybooksPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_playbooks_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_list_playbooks"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_list_playbooks"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = playbook.ListPlaybooksRequest.pb(playbook.ListPlaybooksRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = playbook.ListPlaybooksResponse.to_json(
- playbook.ListPlaybooksResponse()
- )
- req.return_value.content = return_value
-
- request = playbook.ListPlaybooksRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = playbook.ListPlaybooksResponse()
-
- client.list_playbooks(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_playbook_rest_bad_request(request_type=playbook.GetPlaybookRequest):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_playbook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.GetPlaybookRequest,
- dict,
- ],
-)
-def test_get_playbook_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.Playbook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_playbook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, playbook.Playbook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.goal == "goal_value"
- assert response.token_count == 1193
- assert response.referenced_playbooks == ["referenced_playbooks_value"]
- assert response.referenced_flows == ["referenced_flows_value"]
- assert response.referenced_tools == ["referenced_tools_value"]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_playbook_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_get_playbook"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_get_playbook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = playbook.GetPlaybookRequest.pb(playbook.GetPlaybookRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = playbook.Playbook.to_json(playbook.Playbook())
- req.return_value.content = return_value
-
- request = playbook.GetPlaybookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = playbook.Playbook()
-
- client.get_playbook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_playbook_rest_bad_request(
- request_type=gcdc_playbook.UpdatePlaybookRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "playbook": {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_playbook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_playbook.UpdatePlaybookRequest,
- dict,
- ],
-)
-def test_update_playbook_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "playbook": {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- }
- request_init["playbook"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4",
- "display_name": "display_name_value",
- "goal": "goal_value",
- "input_parameter_definitions": [
- {"name": "name_value", "type_": 1, "description": "description_value"}
- ],
- "output_parameter_definitions": {},
- "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
- "token_count": 1193,
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "referenced_playbooks": [
- "referenced_playbooks_value1",
- "referenced_playbooks_value2",
- ],
- "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
- "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
- "llm_model_settings": {
- "model": "model_value",
- "prompt_text": "prompt_text_value",
- },
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_playbook.UpdatePlaybookRequest.meta.fields["playbook"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["playbook"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["playbook"][field])):
- del request_init["playbook"][field][i][subfield]
- else:
- del request_init["playbook"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_playbook.Playbook(
- name="name_value",
- display_name="display_name_value",
- goal="goal_value",
- token_count=1193,
- referenced_playbooks=["referenced_playbooks_value"],
- referenced_flows=["referenced_flows_value"],
- referenced_tools=["referenced_tools_value"],
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_playbook.Playbook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_playbook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_playbook.Playbook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.goal == "goal_value"
- assert response.token_count == 1193
- assert response.referenced_playbooks == ["referenced_playbooks_value"]
- assert response.referenced_flows == ["referenced_flows_value"]
- assert response.referenced_tools == ["referenced_tools_value"]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_playbook_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_update_playbook"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_update_playbook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_playbook.UpdatePlaybookRequest.pb(
- gcdc_playbook.UpdatePlaybookRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_playbook.Playbook.to_json(gcdc_playbook.Playbook())
- req.return_value.content = return_value
-
- request = gcdc_playbook.UpdatePlaybookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_playbook.Playbook()
-
- client.update_playbook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_playbook_version_rest_bad_request(
- request_type=playbook.CreatePlaybookVersionRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_playbook_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.CreatePlaybookVersionRequest,
- dict,
- ],
-)
-def test_create_playbook_version_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request_init["playbook_version"] = {
- "name": "name_value",
- "description": "description_value",
- "playbook": {
- "name": "name_value",
- "display_name": "display_name_value",
- "goal": "goal_value",
- "input_parameter_definitions": [
- {"name": "name_value", "type_": 1, "description": "description_value"}
- ],
- "output_parameter_definitions": {},
- "instruction": {"steps": [{"text": "text_value", "steps": {}}]},
- "token_count": 1193,
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "referenced_playbooks": [
- "referenced_playbooks_value1",
- "referenced_playbooks_value2",
- ],
- "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"],
- "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"],
- "llm_model_settings": {
- "model": "model_value",
- "prompt_text": "prompt_text_value",
- },
- },
- "examples": [
- {
- "name": "name_value",
- "playbook_input": {
- "preceding_conversation_summary": "preceding_conversation_summary_value",
- "action_parameters": {"fields": {}},
- },
- "playbook_output": {
- "execution_summary": "execution_summary_value",
- "action_parameters": {},
- },
- "actions": [
- {
- "user_utterance": {"text": "text_value"},
- "agent_utterance": {"text": "text_value"},
- "tool_use": {
- "tool": "tool_value",
- "action": "action_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- },
- "playbook_invocation": {
- "playbook": "playbook_value",
- "playbook_input": {},
- "playbook_output": {},
- "playbook_state": 1,
- },
- "flow_invocation": {
- "flow": "flow_value",
- "input_action_parameters": {},
- "output_action_parameters": {},
- "flow_state": 1,
- },
- }
- ],
- "display_name": "display_name_value",
- "description": "description_value",
- "token_count": 1193,
- "create_time": {},
- "update_time": {},
- "conversation_state": 1,
- "language_code": "language_code_value",
- }
- ],
- "update_time": {},
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = playbook.CreatePlaybookVersionRequest.meta.fields["playbook_version"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["playbook_version"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["playbook_version"][field])):
- del request_init["playbook_version"][field][i][subfield]
- else:
- del request_init["playbook_version"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.PlaybookVersion(
- name="name_value",
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.PlaybookVersion.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_playbook_version(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, playbook.PlaybookVersion)
- assert response.name == "name_value"
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_playbook_version_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_create_playbook_version"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_create_playbook_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = playbook.CreatePlaybookVersionRequest.pb(
- playbook.CreatePlaybookVersionRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = playbook.PlaybookVersion.to_json(playbook.PlaybookVersion())
- req.return_value.content = return_value
-
- request = playbook.CreatePlaybookVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = playbook.PlaybookVersion()
-
- client.create_playbook_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_playbook_version_rest_bad_request(
- request_type=playbook.GetPlaybookVersionRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_playbook_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.GetPlaybookVersionRequest,
- dict,
- ],
-)
-def test_get_playbook_version_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.PlaybookVersion(
- name="name_value",
- description="description_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.PlaybookVersion.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_playbook_version(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, playbook.PlaybookVersion)
- assert response.name == "name_value"
- assert response.description == "description_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_playbook_version_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
- )
- client = PlaybooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "post_get_playbook_version"
- ) as post, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_get_playbook_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = playbook.GetPlaybookVersionRequest.pb(
- playbook.GetPlaybookVersionRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = playbook.PlaybookVersion.to_json(playbook.PlaybookVersion())
- req.return_value.content = return_value
-
- request = playbook.GetPlaybookVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = playbook.PlaybookVersion()
-
- client.get_playbook_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_playbook_versions_rest_bad_request(
- request_type=playbook.ListPlaybookVersionsRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_playbook_versions(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.ListPlaybookVersionsRequest,
- dict,
- ],
-)
-def test_list_playbook_versions_rest_call_success(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = playbook.ListPlaybookVersionsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_playbook_versions(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListPlaybookVersionsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_playbook_versions_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
)
client = PlaybooksClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -8216,12 +7763,12 @@ def test_list_playbook_versions_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = playbook.ListPlaybookVersionsResponse.to_json(
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = playbook.ListPlaybookVersionsResponse.to_json(
playbook.ListPlaybookVersionsResponse()
)
- req.return_value.content = return_value
request = playbook.ListPlaybookVersionsRequest()
metadata = [
@@ -8243,15 +7790,17 @@ def test_list_playbook_versions_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_delete_playbook_version_rest_bad_request(
- request_type=playbook.DeletePlaybookVersionRequest,
+def test_list_playbook_versions_rest_bad_request(
+ transport: str = "rest", request_type=playbook.ListPlaybookVersionsRequest
):
client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
}
request = request_type(**request_init)
@@ -8260,342 +7809,355 @@ def test_delete_playbook_version_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.delete_playbook_version(request)
+ client.list_playbook_versions(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- playbook.DeletePlaybookVersionRequest,
- dict,
- ],
-)
-def test_delete_playbook_version_rest_call_success(request_type):
+def test_list_playbook_versions_rest_flattened():
client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = playbook.ListPlaybookVersionsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
+ # Convert return value to protobuf type
+ return_value = playbook.ListPlaybookVersionsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_playbook_version(request)
- # Establish that the response is the type that we expect.
- assert response is None
+ client.list_playbook_versions(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions"
+ % client.transport._host,
+ args[1],
+ )
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_playbook_version_rest_interceptors(null_interceptor):
- transport = transports.PlaybooksRestTransport(
+def test_list_playbook_versions_rest_flattened_error(transport: str = "rest"):
+ client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ transport=transport,
)
- client = PlaybooksClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.PlaybooksRestInterceptor, "pre_delete_playbook_version"
- ) as pre:
- pre.assert_not_called()
- pb_message = playbook.DeletePlaybookVersionRequest.pb(
- playbook.DeletePlaybookVersionRequest()
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_playbook_versions(
+ playbook.ListPlaybookVersionsRequest(),
+ parent="parent_value",
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- request = playbook.DeletePlaybookVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
+def test_list_playbook_versions_rest_pager(transport: str = "rest"):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- client.delete_playbook_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # TODO(kbandes): remove this mock unless there's a good reason for it.
+ # with mock.patch.object(path_template, 'transcode') as transcode:
+ # Set the response as a series of pages
+ response = (
+ playbook.ListPlaybookVersionsResponse(
+ playbook_versions=[
+ playbook.PlaybookVersion(),
+ playbook.PlaybookVersion(),
+ playbook.PlaybookVersion(),
+ ],
+ next_page_token="abc",
+ ),
+ playbook.ListPlaybookVersionsResponse(
+ playbook_versions=[],
+ next_page_token="def",
+ ),
+ playbook.ListPlaybookVersionsResponse(
+ playbook_versions=[
+ playbook.PlaybookVersion(),
+ ],
+ next_page_token="ghi",
+ ),
+ playbook.ListPlaybookVersionsResponse(
+ playbook_versions=[
+ playbook.PlaybookVersion(),
+ playbook.PlaybookVersion(),
+ ],
+ ),
)
+ # Two responses for two calls
+ response = response + response
- pre.assert_called_once()
+ # Wrap the values into proper Response objs
+ response = tuple(
+ playbook.ListPlaybookVersionsResponse.to_json(x) for x in response
+ )
+ return_values = tuple(Response() for i in response)
+ for return_val, response_val in zip(return_values, response):
+ return_val._content = response_val.encode("UTF-8")
+ return_val.status_code = 200
+ req.side_effect = return_values
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4"
+ }
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
+ pager = client.list_playbook_versions(request=sample_request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, playbook.PlaybookVersion) for i in results)
+
+ pages = list(client.list_playbook_versions(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.GetLocationRequest,
+ playbook.DeletePlaybookVersionRequest,
dict,
],
)
-def test_get_location_rest(request_type):
+def test_delete_playbook_version_rest(request_type):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = None
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.get_location(request)
+ response = client.delete_playbook_version(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
+ assert response is None
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+def test_delete_playbook_version_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Ensure method has been cached
+ assert (
+ client._transport.delete_playbook_version
+ in client._transport._wrapped_methods
+ )
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.delete_playbook_version
+ ] = mock_rpc
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ request = {}
+ client.delete_playbook_version(request)
- req.return_value = response_value
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
- response = client.list_locations(request)
+ client.delete_playbook_version(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
+def test_delete_playbook_version_rest_required_fields(
+ request_type=playbook.DeletePlaybookVersionRequest,
):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport_class = transports.PlaybooksRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_playbook_version._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_playbook_version._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1/operations/sample2"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "delete",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- req.return_value = response_value
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- response = client.cancel_operation(request)
+ response = client.delete_playbook_version(request)
- # Establish that the response is the type that we expect.
- assert response is None
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_delete_playbook_version_rest_unset_required_fields():
+ transport = transports.PlaybooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
+ unset_fields = transport.delete_playbook_version._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = PlaybooksClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_playbook_version_rest_interceptors(null_interceptor):
+ transport = transports.PlaybooksRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(),
+ )
+ client = PlaybooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.PlaybooksRestInterceptor, "pre_delete_playbook_version"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = playbook.DeletePlaybookVersionRequest.pb(
+ playbook.DeletePlaybookVersionRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- req.return_value = response_value
+ request = playbook.DeletePlaybookVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- response = client.get_operation(request)
+ client.delete_playbook_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_delete_playbook_version_rest_bad_request(
+ transport: str = "rest", request_type=playbook.DeletePlaybookVersionRequest
):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -8603,241 +8165,179 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
+ client.delete_playbook_version(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+def test_delete_playbook_version_rest_flattened():
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
+ client.delete_playbook_version(**mock_args)
-def test_initialize_client_w_rest():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_playbook_empty_call_rest():
+def test_delete_playbook_version_rest_flattened_error(transport: str = "rest"):
client = PlaybooksClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_playbook), "__call__") as call:
- client.create_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.CreatePlaybookRequest()
-
- assert args[0] == request_msg
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_playbook_version(
+ playbook.DeletePlaybookVersionRequest(),
+ name="name_value",
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_playbook_empty_call_rest():
+def test_delete_playbook_version_rest_error():
client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call:
- client.delete_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookRequest()
-
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_playbooks_empty_call_rest():
- client = PlaybooksClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call:
- client.list_playbooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_playbook_empty_call_rest():
- client = PlaybooksClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = PlaybooksClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_playbook), "__call__") as call:
- client.get_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_playbook_empty_call_rest():
- client = PlaybooksClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = PlaybooksClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_playbook), "__call__") as call:
- client.update_playbook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_playbook.UpdatePlaybookRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = PlaybooksClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_playbook_version_empty_call_rest():
- client = PlaybooksClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_playbook_version), "__call__"
- ) as call:
- client.create_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.CreatePlaybookVersionRequest()
-
- assert args[0] == request_msg
+ with pytest.raises(ValueError):
+ client = PlaybooksClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_playbook_version_empty_call_rest():
- client = PlaybooksClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_playbook_version), "__call__"
- ) as call:
- client.get_playbook_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.GetPlaybookVersionRequest()
-
- assert args[0] == request_msg
+ client = PlaybooksClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_playbook_versions_empty_call_rest():
- client = PlaybooksClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.PlaybooksGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_playbook_versions), "__call__"
- ) as call:
- client.list_playbook_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.ListPlaybookVersionsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_playbook_version_empty_call_rest():
- client = PlaybooksClient(
+ transport = transports.PlaybooksGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_playbook_version), "__call__"
- ) as call:
- client.delete_playbook_version(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = playbook.DeletePlaybookVersionRequest()
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.PlaybooksGrpcTransport,
+ transports.PlaybooksGrpcAsyncIOTransport,
+ transports.PlaybooksRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = PlaybooksClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -9473,115 +8973,415 @@ def test_parse_common_billing_account_path():
}
path = PlaybooksClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = PlaybooksClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = PlaybooksClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = PlaybooksClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = PlaybooksClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PlaybooksClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = PlaybooksClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = PlaybooksClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PlaybooksClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = PlaybooksClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = PlaybooksClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PlaybooksClient.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 = PlaybooksClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = PlaybooksClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = PlaybooksClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.PlaybooksTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.PlaybooksTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = PlaybooksClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = PlaybooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "scallop"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = PlaybooksClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "abalone",
- }
- path = PlaybooksClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = PlaybooksClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "squid"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = PlaybooksClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "clam",
- }
- path = PlaybooksClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = PlaybooksClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "whelk"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = PlaybooksClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "octopus",
- }
- path = PlaybooksClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = PlaybooksClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "oyster"
- location = "nudibranch"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = PlaybooksClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- }
- path = PlaybooksClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = PlaybooksClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.PlaybooksTransport, "_prep_wrapped_messages"
- ) as prep:
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.PlaybooksTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = PlaybooksClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -9611,7 +9411,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9664,7 +9464,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9709,7 +9509,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -9750,7 +9550,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9805,7 +9605,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9852,7 +9652,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -9895,7 +9695,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -9950,7 +9750,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -9997,7 +9797,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -10040,7 +9840,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10095,7 +9895,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -10142,7 +9942,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10185,7 +9985,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -10237,7 +10037,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = PlaybooksAsyncClient(credentials=async_anonymous_credentials())
+ client = PlaybooksAsyncClient(credentials=ga_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.
@@ -10283,7 +10083,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -10299,41 +10099,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = PlaybooksAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = PlaybooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = PlaybooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py
index 165e95c069cd..8b90238bd9a0 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,6 +36,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import (
SecuritySettingsServiceAsyncClient,
@@ -67,24 +57,10 @@
from google.cloud.dialogflowcx_v3beta1.types import security_settings
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1282,6 +1258,27 @@ def test_create_security_settings(request_type, transport: str = "grpc"):
]
+def test_create_security_settings_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 = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_security_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest()
+
+
def test_create_security_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1352,6 +1349,39 @@ def test_create_security_settings_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_security_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_security_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ )
+ )
+ response = await client.create_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest()
+
+
@pytest.mark.asyncio
async def test_create_security_settings_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1360,7 +1390,7 @@ async def test_create_security_settings_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1375,23 +1405,27 @@ async def test_create_security_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_security_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_security_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_security_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1400,7 +1434,7 @@ async def test_create_security_settings_async(
request_type=gcdc_security_settings.CreateSecuritySettingsRequest,
):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1492,7 +1526,7 @@ def test_create_security_settings_field_headers():
@pytest.mark.asyncio
async def test_create_security_settings_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1575,7 +1609,7 @@ def test_create_security_settings_flattened_error():
@pytest.mark.asyncio
async def test_create_security_settings_flattened_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1612,7 +1646,7 @@ async def test_create_security_settings_flattened_async():
@pytest.mark.asyncio
async def test_create_security_settings_flattened_error_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1688,6 +1722,27 @@ def test_get_security_settings(request_type, transport: str = "grpc"):
]
+def test_get_security_settings_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 = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_security_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.GetSecuritySettingsRequest()
+
+
def test_get_security_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1758,6 +1813,39 @@ def test_get_security_settings_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_security_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_security_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ )
+ )
+ response = await client.get_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.GetSecuritySettingsRequest()
+
+
@pytest.mark.asyncio
async def test_get_security_settings_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1766,7 +1854,7 @@ async def test_get_security_settings_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1781,23 +1869,27 @@ async def test_get_security_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_security_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_security_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_security_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1806,7 +1898,7 @@ async def test_get_security_settings_async(
request_type=security_settings.GetSecuritySettingsRequest,
):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1898,7 +1990,7 @@ def test_get_security_settings_field_headers():
@pytest.mark.asyncio
async def test_get_security_settings_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1972,7 +2064,7 @@ def test_get_security_settings_flattened_error():
@pytest.mark.asyncio
async def test_get_security_settings_flattened_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2003,7 +2095,7 @@ async def test_get_security_settings_flattened_async():
@pytest.mark.asyncio
async def test_get_security_settings_flattened_error_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2076,6 +2168,27 @@ def test_update_security_settings(request_type, transport: str = "grpc"):
]
+def test_update_security_settings_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 = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_security_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest()
+
+
def test_update_security_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2142,6 +2255,39 @@ def test_update_security_settings_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_security_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_security_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ )
+ )
+ response = await client.update_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest()
+
+
@pytest.mark.asyncio
async def test_update_security_settings_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2150,7 +2296,7 @@ async def test_update_security_settings_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2165,23 +2311,27 @@ async def test_update_security_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_security_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_security_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_security_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2190,7 +2340,7 @@ async def test_update_security_settings_async(
request_type=gcdc_security_settings.UpdateSecuritySettingsRequest,
):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2282,7 +2432,7 @@ def test_update_security_settings_field_headers():
@pytest.mark.asyncio
async def test_update_security_settings_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2365,7 +2515,7 @@ def test_update_security_settings_flattened_error():
@pytest.mark.asyncio
async def test_update_security_settings_flattened_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2402,7 +2552,7 @@ async def test_update_security_settings_flattened_async():
@pytest.mark.asyncio
async def test_update_security_settings_flattened_error_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2455,6 +2605,27 @@ def test_list_security_settings(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_security_settings_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 = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_security_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.ListSecuritySettingsRequest()
+
+
def test_list_security_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2527,6 +2698,31 @@ def test_list_security_settings_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_security_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_security_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ security_settings.ListSecuritySettingsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.ListSecuritySettingsRequest()
+
+
@pytest.mark.asyncio
async def test_list_security_settings_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2535,7 +2731,7 @@ async def test_list_security_settings_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2550,23 +2746,27 @@ async def test_list_security_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_security_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_security_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_security_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2575,7 +2775,7 @@ async def test_list_security_settings_async(
request_type=security_settings.ListSecuritySettingsRequest,
):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2645,7 +2845,7 @@ def test_list_security_settings_field_headers():
@pytest.mark.asyncio
async def test_list_security_settings_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2719,7 +2919,7 @@ def test_list_security_settings_flattened_error():
@pytest.mark.asyncio
async def test_list_security_settings_flattened_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2750,7 +2950,7 @@ async def test_list_security_settings_flattened_async():
@pytest.mark.asyncio
async def test_list_security_settings_flattened_error_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2802,16 +3002,12 @@ def test_list_security_settings_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_security_settings(request={}, retry=retry, timeout=timeout)
+ pager = client.list_security_settings(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -2864,7 +3060,7 @@ def test_list_security_settings_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_security_settings_async_pager():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2916,7 +3112,7 @@ async def test_list_security_settings_async_pager():
@pytest.mark.asyncio
async def test_list_security_settings_async_pages():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2999,6 +3195,27 @@ def test_delete_security_settings(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_security_settings_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 = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_security_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.DeleteSecuritySettingsRequest()
+
+
def test_delete_security_settings_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3070,14 +3287,35 @@ def test_delete_security_settings_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_delete_security_settings_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
-):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+async def test_delete_security_settings_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_security_settings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_security_settings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == security_settings.DeleteSecuritySettingsRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_security_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3092,23 +3330,27 @@ async def test_delete_security_settings_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_security_settings
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_security_settings(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_security_settings(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3117,7 +3359,7 @@ async def test_delete_security_settings_async(
request_type=security_settings.DeleteSecuritySettingsRequest,
):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3182,7 +3424,7 @@ def test_delete_security_settings_field_headers():
@pytest.mark.asyncio
async def test_delete_security_settings_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3254,7 +3496,7 @@ def test_delete_security_settings_flattened_error():
@pytest.mark.asyncio
async def test_delete_security_settings_flattened_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3283,7 +3525,7 @@ async def test_delete_security_settings_flattened_async():
@pytest.mark.asyncio
async def test_delete_security_settings_flattened_error_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3295,6 +3537,157 @@ async def test_delete_security_settings_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_security_settings.CreateSecuritySettingsRequest,
+ dict,
+ ],
+)
+def test_create_security_settings_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init["security_settings"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "redaction_strategy": 1,
+ "redaction_scope": 2,
+ "inspect_template": "inspect_template_value",
+ "deidentify_template": "deidentify_template_value",
+ "retention_window_days": 2271,
+ "retention_strategy": 1,
+ "purge_data_types": [1],
+ "audio_export_settings": {
+ "gcs_bucket": "gcs_bucket_value",
+ "audio_export_pattern": "audio_export_pattern_value",
+ "enable_audio_redaction": True,
+ "audio_format": 1,
+ "store_tts_audio": True,
+ },
+ "insights_export_settings": {"enable_insights_export": True},
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_security_settings.CreateSecuritySettingsRequest.meta.fields[
+ "security_settings"
+ ]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["security_settings"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["security_settings"][field])):
+ del request_init["security_settings"][field][i][subfield]
+ else:
+ del request_init["security_settings"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ retention_window_days=2271,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_security_settings(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_security_settings.SecuritySettings)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.redaction_strategy
+ == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
+ )
+ assert (
+ response.redaction_scope
+ == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
+ )
+ assert response.inspect_template == "inspect_template_value"
+ assert response.deidentify_template == "deidentify_template_value"
+ assert response.purge_data_types == [
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ]
+
+
def test_create_security_settings_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3428,42 +3821,126 @@ def test_create_security_settings_rest_unset_required_fields():
)
-def test_create_security_settings_rest_flattened():
- client = SecuritySettingsServiceClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_security_settings_rest_interceptors(null_interceptor):
+ transport = transports.SecuritySettingsServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.SecuritySettingsServiceRestInterceptor(),
)
+ client = SecuritySettingsServiceClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor,
+ "post_create_security_settings",
+ ) as post, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor,
+ "pre_create_security_settings",
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_security_settings.CreateSecuritySettingsRequest.pb(
+ gcdc_security_settings.CreateSecuritySettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_security_settings.SecuritySettings()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_security_settings.SecuritySettings.to_json(
+ gcdc_security_settings.SecuritySettings()
+ )
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2"}
+ request = gcdc_security_settings.CreateSecuritySettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_security_settings.SecuritySettings()
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- security_settings=gcdc_security_settings.SecuritySettings(
- name="name_value"
- ),
+ client.create_security_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ pre.assert_called_once()
+ post.assert_called_once()
- client.create_security_settings(**mock_args)
- # Establish that the underlying call was made with the expected
- # request object values.
+def test_create_security_settings_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_security_settings.CreateSecuritySettingsRequest,
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_security_settings(request)
+
+
+def test_create_security_settings_rest_flattened():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_security_settings.SecuritySettings()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2"}
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ security_settings=gcdc_security_settings.SecuritySettings(
+ name="name_value"
+ ),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.create_security_settings(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
@@ -3491,6 +3968,77 @@ def test_create_security_settings_rest_flattened_error(transport: str = "rest"):
)
+def test_create_security_settings_rest_error():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ security_settings.GetSecuritySettingsRequest,
+ dict,
+ ],
+)
+def test_get_security_settings_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ retention_window_days=2271,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = security_settings.SecuritySettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_security_settings(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, security_settings.SecuritySettings)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.redaction_strategy
+ == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
+ )
+ assert (
+ response.redaction_scope
+ == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
+ )
+ assert response.inspect_template == "inspect_template_value"
+ assert response.deidentify_template == "deidentify_template_value"
+ assert response.purge_data_types == [
+ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ]
+
+
def test_get_security_settings_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3615,6 +4163,89 @@ def test_get_security_settings_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_security_settings_rest_interceptors(null_interceptor):
+ transport = transports.SecuritySettingsServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SecuritySettingsServiceRestInterceptor(),
+ )
+ client = SecuritySettingsServiceClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor, "post_get_security_settings"
+ ) as post, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor, "pre_get_security_settings"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = security_settings.GetSecuritySettingsRequest.pb(
+ security_settings.GetSecuritySettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = security_settings.SecuritySettings.to_json(
+ security_settings.SecuritySettings()
+ )
+
+ request = security_settings.GetSecuritySettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = security_settings.SecuritySettings()
+
+ client.get_security_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_security_settings_rest_bad_request(
+ transport: str = "rest", request_type=security_settings.GetSecuritySettingsRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_security_settings(request)
+
+
def test_get_security_settings_rest_flattened():
client = SecuritySettingsServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3674,43 +4305,204 @@ def test_get_security_settings_rest_flattened_error(transport: str = "rest"):
)
-def test_update_security_settings_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.update_security_settings
- in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.update_security_settings
- ] = mock_rpc
-
- request = {}
- client.update_security_settings(request)
+def test_get_security_settings_rest_error():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
- client.update_security_settings(request)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_security_settings.UpdateSecuritySettingsRequest,
+ dict,
+ ],
+)
+def test_update_security_settings_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Establish that a new wrapper was not created for this call
+ # send a request that will satisfy transcoding
+ request_init = {
+ "security_settings": {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ }
+ request_init["security_settings"] = {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3",
+ "display_name": "display_name_value",
+ "redaction_strategy": 1,
+ "redaction_scope": 2,
+ "inspect_template": "inspect_template_value",
+ "deidentify_template": "deidentify_template_value",
+ "retention_window_days": 2271,
+ "retention_strategy": 1,
+ "purge_data_types": [1],
+ "audio_export_settings": {
+ "gcs_bucket": "gcs_bucket_value",
+ "audio_export_pattern": "audio_export_pattern_value",
+ "enable_audio_redaction": True,
+ "audio_format": 1,
+ "store_tts_audio": True,
+ },
+ "insights_export_settings": {"enable_insights_export": True},
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_security_settings.UpdateSecuritySettingsRequest.meta.fields[
+ "security_settings"
+ ]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["security_settings"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["security_settings"][field])):
+ del request_init["security_settings"][field][i][subfield]
+ else:
+ del request_init["security_settings"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_security_settings.SecuritySettings(
+ name="name_value",
+ display_name="display_name_value",
+ redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
+ redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
+ inspect_template="inspect_template_value",
+ deidentify_template="deidentify_template_value",
+ purge_data_types=[
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ],
+ retention_window_days=2271,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_security_settings(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_security_settings.SecuritySettings)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.redaction_strategy
+ == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
+ )
+ assert (
+ response.redaction_scope
+ == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
+ )
+ assert response.inspect_template == "inspect_template_value"
+ assert response.deidentify_template == "deidentify_template_value"
+ assert response.purge_data_types == [
+ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
+ ]
+
+
+def test_update_security_settings_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_security_settings
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_security_settings
+ ] = mock_rpc
+
+ request = {}
+ client.update_security_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_security_settings(request)
+
+ # Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
@@ -3804,45 +4596,133 @@ def test_update_security_settings_rest_unset_required_fields():
)
-def test_update_security_settings_rest_flattened():
- client = SecuritySettingsServiceClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_security_settings_rest_interceptors(null_interceptor):
+ transport = transports.SecuritySettingsServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.SecuritySettingsServiceRestInterceptor(),
)
+ client = SecuritySettingsServiceClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor,
+ "post_update_security_settings",
+ ) as post, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor,
+ "pre_update_security_settings",
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_security_settings.UpdateSecuritySettingsRequest.pb(
+ gcdc_security_settings.UpdateSecuritySettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_security_settings.SecuritySettings()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_security_settings.SecuritySettings.to_json(
+ gcdc_security_settings.SecuritySettings()
+ )
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "security_settings": {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- }
+ request = gcdc_security_settings.UpdateSecuritySettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_security_settings.SecuritySettings()
- # get truthy value for each flattened field
- mock_args = dict(
- security_settings=gcdc_security_settings.SecuritySettings(
- name="name_value"
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client.update_security_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+ pre.assert_called_once()
+ post.assert_called_once()
- client.update_security_settings(**mock_args)
- # Establish that the underlying call was made with the expected
+def test_update_security_settings_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_security_settings.UpdateSecuritySettingsRequest,
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "security_settings": {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_security_settings(request)
+
+
+def test_update_security_settings_rest_flattened():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_security_settings.SecuritySettings()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "security_settings": {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ security_settings=gcdc_security_settings.SecuritySettings(
+ name="name_value"
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.update_security_settings(**mock_args)
+
+ # Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
@@ -3871,6 +4751,52 @@ def test_update_security_settings_rest_flattened_error(transport: str = "rest"):
)
+def test_update_security_settings_rest_error():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ security_settings.ListSecuritySettingsRequest,
+ dict,
+ ],
+)
+def test_list_security_settings_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = security_settings.ListSecuritySettingsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = security_settings.ListSecuritySettingsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_security_settings(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListSecuritySettingsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_security_settings_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4012,6 +4938,89 @@ def test_list_security_settings_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_security_settings_rest_interceptors(null_interceptor):
+ transport = transports.SecuritySettingsServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SecuritySettingsServiceRestInterceptor(),
+ )
+ client = SecuritySettingsServiceClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor, "post_list_security_settings"
+ ) as post, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor, "pre_list_security_settings"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = security_settings.ListSecuritySettingsRequest.pb(
+ security_settings.ListSecuritySettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ security_settings.ListSecuritySettingsResponse.to_json(
+ security_settings.ListSecuritySettingsResponse()
+ )
+ )
+
+ request = security_settings.ListSecuritySettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = security_settings.ListSecuritySettingsResponse()
+
+ client.list_security_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_security_settings_rest_bad_request(
+ transport: str = "rest", request_type=security_settings.ListSecuritySettingsRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_security_settings(request)
+
+
def test_list_security_settings_rest_flattened():
client = SecuritySettingsServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4132,6 +5141,43 @@ def test_list_security_settings_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ security_settings.DeleteSecuritySettingsRequest,
+ dict,
+ ],
+)
+def test_delete_security_settings_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_security_settings(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_security_settings_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4253,16 +5299,93 @@ def test_delete_security_settings_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_delete_security_settings_rest_flattened():
- client = SecuritySettingsServiceClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_security_settings_rest_interceptors(null_interceptor):
+ transport = transports.SecuritySettingsServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.SecuritySettingsServiceRestInterceptor(),
)
+ client = SecuritySettingsServiceClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SecuritySettingsServiceRestInterceptor,
+ "pre_delete_security_settings",
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = security_settings.DeleteSecuritySettingsRequest.pb(
+ security_settings.DeleteSecuritySettingsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = security_settings.DeleteSecuritySettingsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_security_settings(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_security_settings_rest_bad_request(
+ transport: str = "rest",
+ request_type=security_settings.DeleteSecuritySettingsRequest,
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/securitySettings/sample3"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_security_settings(request)
+
+
+def test_delete_security_settings_rest_flattened():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
# get arguments that satisfy an http rule for this method
sample_request = {
@@ -4310,6 +5433,12 @@ def test_delete_security_settings_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_security_settings_rest_error():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.SecuritySettingsServiceGrpcTransport(
@@ -4402,1586 +5531,18 @@ def test_transport_adc(transport_class):
adc.assert_called_once()
-def test_transport_kind_grpc():
- transport = SecuritySettingsServiceClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_security_settings_empty_call_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_security_settings), "__call__"
- ) as call:
- call.return_value = gcdc_security_settings.SecuritySettings()
- client.create_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.CreateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_security_settings_empty_call_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_security_settings), "__call__"
- ) as call:
- call.return_value = security_settings.SecuritySettings()
- client.get_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.GetSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_security_settings_empty_call_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_security_settings), "__call__"
- ) as call:
- call.return_value = gcdc_security_settings.SecuritySettings()
- client.update_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.UpdateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_security_settings_empty_call_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_security_settings), "__call__"
- ) as call:
- call.return_value = security_settings.ListSecuritySettingsResponse()
- client.list_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.ListSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_security_settings_empty_call_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_security_settings), "__call__"
- ) as call:
- call.return_value = None
- client.delete_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.DeleteSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = SecuritySettingsServiceAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_security_settings_empty_call_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_security_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- )
- )
- await client.create_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.CreateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_security_settings_empty_call_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_security_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- )
- )
- await client.get_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.GetSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_security_settings_empty_call_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_security_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- )
- )
- await client.update_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.UpdateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_security_settings_empty_call_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_security_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- security_settings.ListSecuritySettingsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.ListSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_security_settings_empty_call_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_security_settings), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.DeleteSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = SecuritySettingsServiceClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_create_security_settings_rest_bad_request(
- request_type=gcdc_security_settings.CreateSecuritySettingsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_security_settings(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_security_settings.CreateSecuritySettingsRequest,
- dict,
- ],
-)
-def test_create_security_settings_rest_call_success(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["security_settings"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "redaction_strategy": 1,
- "redaction_scope": 2,
- "inspect_template": "inspect_template_value",
- "deidentify_template": "deidentify_template_value",
- "retention_window_days": 2271,
- "retention_strategy": 1,
- "purge_data_types": [1],
- "audio_export_settings": {
- "gcs_bucket": "gcs_bucket_value",
- "audio_export_pattern": "audio_export_pattern_value",
- "enable_audio_redaction": True,
- "audio_format": 1,
- "store_tts_audio": True,
- },
- "insights_export_settings": {"enable_insights_export": True},
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_security_settings.CreateSecuritySettingsRequest.meta.fields[
- "security_settings"
- ]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["security_settings"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["security_settings"][field])):
- del request_init["security_settings"][field][i][subfield]
- else:
- del request_init["security_settings"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- retention_window_days=2271,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_security_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_security_settings.SecuritySettings)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert (
- response.redaction_strategy
- == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
- )
- assert (
- response.redaction_scope
- == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
- )
- assert response.inspect_template == "inspect_template_value"
- assert response.deidentify_template == "deidentify_template_value"
- assert response.purge_data_types == [
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_security_settings_rest_interceptors(null_interceptor):
- transport = transports.SecuritySettingsServiceRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SecuritySettingsServiceRestInterceptor(),
- )
- client = SecuritySettingsServiceClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor,
- "post_create_security_settings",
- ) as post, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor,
- "pre_create_security_settings",
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_security_settings.CreateSecuritySettingsRequest.pb(
- gcdc_security_settings.CreateSecuritySettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_security_settings.SecuritySettings.to_json(
- gcdc_security_settings.SecuritySettings()
- )
- req.return_value.content = return_value
-
- request = gcdc_security_settings.CreateSecuritySettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_security_settings.SecuritySettings()
-
- client.create_security_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_security_settings_rest_bad_request(
- request_type=security_settings.GetSecuritySettingsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_security_settings(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- security_settings.GetSecuritySettingsRequest,
- dict,
- ],
-)
-def test_get_security_settings_rest_call_success(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- retention_window_days=2271,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = security_settings.SecuritySettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_security_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, security_settings.SecuritySettings)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert (
- response.redaction_strategy
- == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
- )
- assert (
- response.redaction_scope
- == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
- )
- assert response.inspect_template == "inspect_template_value"
- assert response.deidentify_template == "deidentify_template_value"
- assert response.purge_data_types == [
- security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_security_settings_rest_interceptors(null_interceptor):
- transport = transports.SecuritySettingsServiceRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SecuritySettingsServiceRestInterceptor(),
- )
- client = SecuritySettingsServiceClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor, "post_get_security_settings"
- ) as post, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor, "pre_get_security_settings"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = security_settings.GetSecuritySettingsRequest.pb(
- security_settings.GetSecuritySettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = security_settings.SecuritySettings.to_json(
- security_settings.SecuritySettings()
- )
- req.return_value.content = return_value
-
- request = security_settings.GetSecuritySettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = security_settings.SecuritySettings()
-
- client.get_security_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_security_settings_rest_bad_request(
- request_type=gcdc_security_settings.UpdateSecuritySettingsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "security_settings": {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_security_settings(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_security_settings.UpdateSecuritySettingsRequest,
- dict,
- ],
-)
-def test_update_security_settings_rest_call_success(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "security_settings": {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- }
- request_init["security_settings"] = {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3",
- "display_name": "display_name_value",
- "redaction_strategy": 1,
- "redaction_scope": 2,
- "inspect_template": "inspect_template_value",
- "deidentify_template": "deidentify_template_value",
- "retention_window_days": 2271,
- "retention_strategy": 1,
- "purge_data_types": [1],
- "audio_export_settings": {
- "gcs_bucket": "gcs_bucket_value",
- "audio_export_pattern": "audio_export_pattern_value",
- "enable_audio_redaction": True,
- "audio_format": 1,
- "store_tts_audio": True,
- },
- "insights_export_settings": {"enable_insights_export": True},
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_security_settings.UpdateSecuritySettingsRequest.meta.fields[
- "security_settings"
- ]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["security_settings"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["security_settings"][field])):
- del request_init["security_settings"][field][i][subfield]
- else:
- del request_init["security_settings"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_security_settings.SecuritySettings(
- name="name_value",
- display_name="display_name_value",
- redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE,
- redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE,
- inspect_template="inspect_template_value",
- deidentify_template="deidentify_template_value",
- purge_data_types=[
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ],
- retention_window_days=2271,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_security_settings.SecuritySettings.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_security_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_security_settings.SecuritySettings)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert (
- response.redaction_strategy
- == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE
- )
- assert (
- response.redaction_scope
- == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE
- )
- assert response.inspect_template == "inspect_template_value"
- assert response.deidentify_template == "deidentify_template_value"
- assert response.purge_data_types == [
- gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY
- ]
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_security_settings_rest_interceptors(null_interceptor):
- transport = transports.SecuritySettingsServiceRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SecuritySettingsServiceRestInterceptor(),
- )
- client = SecuritySettingsServiceClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor,
- "post_update_security_settings",
- ) as post, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor,
- "pre_update_security_settings",
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_security_settings.UpdateSecuritySettingsRequest.pb(
- gcdc_security_settings.UpdateSecuritySettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_security_settings.SecuritySettings.to_json(
- gcdc_security_settings.SecuritySettings()
- )
- req.return_value.content = return_value
-
- request = gcdc_security_settings.UpdateSecuritySettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_security_settings.SecuritySettings()
-
- client.update_security_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_security_settings_rest_bad_request(
- request_type=security_settings.ListSecuritySettingsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_security_settings(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- security_settings.ListSecuritySettingsRequest,
- dict,
- ],
-)
-def test_list_security_settings_rest_call_success(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = security_settings.ListSecuritySettingsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = security_settings.ListSecuritySettingsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_security_settings(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListSecuritySettingsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_security_settings_rest_interceptors(null_interceptor):
- transport = transports.SecuritySettingsServiceRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SecuritySettingsServiceRestInterceptor(),
- )
- client = SecuritySettingsServiceClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor, "post_list_security_settings"
- ) as post, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor, "pre_list_security_settings"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = security_settings.ListSecuritySettingsRequest.pb(
- security_settings.ListSecuritySettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = security_settings.ListSecuritySettingsResponse.to_json(
- security_settings.ListSecuritySettingsResponse()
- )
- req.return_value.content = return_value
-
- request = security_settings.ListSecuritySettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = security_settings.ListSecuritySettingsResponse()
-
- client.list_security_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_security_settings_rest_bad_request(
- request_type=security_settings.DeleteSecuritySettingsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_security_settings(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- security_settings.DeleteSecuritySettingsRequest,
- dict,
- ],
-)
-def test_delete_security_settings_rest_call_success(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/securitySettings/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_security_settings(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_security_settings_rest_interceptors(null_interceptor):
- transport = transports.SecuritySettingsServiceRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SecuritySettingsServiceRestInterceptor(),
- )
- client = SecuritySettingsServiceClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SecuritySettingsServiceRestInterceptor,
- "pre_delete_security_settings",
- ) as pre:
- pre.assert_not_called()
- pb_message = security_settings.DeleteSecuritySettingsRequest.pb(
- security_settings.DeleteSecuritySettingsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = security_settings.DeleteSecuritySettingsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_security_settings(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_security_settings_empty_call_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_security_settings), "__call__"
- ) as call:
- client.create_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.CreateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_security_settings_empty_call_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_security_settings), "__call__"
- ) as call:
- client.get_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.GetSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_security_settings_empty_call_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_security_settings), "__call__"
- ) as call:
- client.update_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_security_settings.UpdateSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_security_settings_empty_call_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_security_settings), "__call__"
- ) as call:
- client.list_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.ListSecuritySettingsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_security_settings_empty_call_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_security_settings), "__call__"
- ) as call:
- client.delete_security_settings(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = security_settings.DeleteSecuritySettingsRequest()
-
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = SecuritySettingsServiceClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6543,115 +6104,415 @@ def test_parse_common_billing_account_path():
}
path = SecuritySettingsServiceClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "winkle"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = SecuritySettingsServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nautilus",
+ }
+ path = SecuritySettingsServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SecuritySettingsServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "scallop"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = SecuritySettingsServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "abalone",
+ }
+ path = SecuritySettingsServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SecuritySettingsServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "squid"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = SecuritySettingsServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "clam",
+ }
+ path = SecuritySettingsServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SecuritySettingsServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "whelk"
+ location = "octopus"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = SecuritySettingsServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ }
+ path = SecuritySettingsServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SecuritySettingsServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = SecuritySettingsServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = SecuritySettingsServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "winkle"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SecuritySettingsServiceClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "nautilus",
- }
- path = SecuritySettingsServiceClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SecuritySettingsServiceClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "scallop"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = SecuritySettingsServiceClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "abalone",
- }
- path = SecuritySettingsServiceClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = SecuritySettingsServiceClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "squid"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SecuritySettingsServiceClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "clam",
- }
- path = SecuritySettingsServiceClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SecuritySettingsServiceClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "whelk"
- location = "octopus"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = SecuritySettingsServiceClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- }
- path = SecuritySettingsServiceClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = SecuritySettingsServiceClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages"
- ) as prep:
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = SecuritySettingsServiceClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6681,7 +6542,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6734,7 +6595,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6779,7 +6640,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6820,7 +6681,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6875,7 +6736,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6922,7 +6783,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6965,7 +6826,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7020,7 +6881,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7067,7 +6928,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -7110,7 +6971,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7165,7 +7026,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7212,7 +7073,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7255,7 +7116,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7310,7 +7171,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials()
+ credentials=ga_credentials.AnonymousCredentials()
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7357,7 +7218,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7373,41 +7234,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = SecuritySettingsServiceAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = SecuritySettingsServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = SecuritySettingsServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py
index 7d2d02ed9156..c0a5380deb18 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -54,6 +36,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import (
SessionEntityTypesAsyncClient,
@@ -68,24 +58,10 @@
from google.cloud.dialogflowcx_v3beta1.types import session_entity_type
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1230,6 +1206,27 @@ def test_list_session_entity_types(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_session_entity_types_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 = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_session_entity_types), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_session_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.ListSessionEntityTypesRequest()
+
+
def test_list_session_entity_types_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1302,6 +1299,31 @@ def test_list_session_entity_types_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_session_entity_types_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_session_entity_types), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session_entity_type.ListSessionEntityTypesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_session_entity_types()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.ListSessionEntityTypesRequest()
+
+
@pytest.mark.asyncio
async def test_list_session_entity_types_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1310,7 +1332,7 @@ async def test_list_session_entity_types_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1325,23 +1347,27 @@ async def test_list_session_entity_types_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_session_entity_types
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_session_entity_types(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_session_entity_types(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1350,7 +1376,7 @@ async def test_list_session_entity_types_async(
request_type=session_entity_type.ListSessionEntityTypesRequest,
):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1420,7 +1446,7 @@ def test_list_session_entity_types_field_headers():
@pytest.mark.asyncio
async def test_list_session_entity_types_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1494,7 +1520,7 @@ def test_list_session_entity_types_flattened_error():
@pytest.mark.asyncio
async def test_list_session_entity_types_flattened_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1525,7 +1551,7 @@ async def test_list_session_entity_types_flattened_async():
@pytest.mark.asyncio
async def test_list_session_entity_types_flattened_error_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1577,18 +1603,12 @@ def test_list_session_entity_types_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_session_entity_types(
- request={}, retry=retry, timeout=timeout
- )
+ pager = client.list_session_entity_types(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1643,7 +1663,7 @@ def test_list_session_entity_types_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_session_entity_types_async_pager():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1697,7 +1717,7 @@ async def test_list_session_entity_types_async_pager():
@pytest.mark.asyncio
async def test_list_session_entity_types_async_pages():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1788,6 +1808,27 @@ def test_get_session_entity_type(request_type, transport: str = "grpc"):
)
+def test_get_session_entity_type_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 = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_session_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.GetSessionEntityTypeRequest()
+
+
def test_get_session_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1858,6 +1899,32 @@ def test_get_session_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_session_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_session_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+ )
+ response = await client.get_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.GetSessionEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_get_session_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1866,7 +1933,7 @@ async def test_get_session_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1881,23 +1948,27 @@ async def test_get_session_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_session_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_session_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_session_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1906,7 +1977,7 @@ async def test_get_session_entity_type_async(
request_type=session_entity_type.GetSessionEntityTypeRequest,
):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1981,7 +2052,7 @@ def test_get_session_entity_type_field_headers():
@pytest.mark.asyncio
async def test_get_session_entity_type_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2055,7 +2126,7 @@ def test_get_session_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_get_session_entity_type_flattened_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2086,7 +2157,7 @@ async def test_get_session_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_get_session_entity_type_flattened_error_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2141,6 +2212,27 @@ def test_create_session_entity_type(request_type, transport: str = "grpc"):
)
+def test_create_session_entity_type_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 = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_session_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest()
+
+
def test_create_session_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2211,6 +2303,32 @@ def test_create_session_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_session_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_session_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+ )
+ response = await client.create_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_create_session_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2219,7 +2337,7 @@ async def test_create_session_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2234,23 +2352,27 @@ async def test_create_session_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_session_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_session_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_session_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2259,7 +2381,7 @@ async def test_create_session_entity_type_async(
request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest,
):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2334,7 +2456,7 @@ def test_create_session_entity_type_field_headers():
@pytest.mark.asyncio
async def test_create_session_entity_type_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2417,7 +2539,7 @@ def test_create_session_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_create_session_entity_type_flattened_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2454,7 +2576,7 @@ async def test_create_session_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_create_session_entity_type_flattened_error_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2512,6 +2634,27 @@ def test_update_session_entity_type(request_type, transport: str = "grpc"):
)
+def test_update_session_entity_type_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 = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_session_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
+
+
def test_update_session_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2578,6 +2721,32 @@ def test_update_session_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_session_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_session_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+ )
+ response = await client.update_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_update_session_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2586,7 +2755,7 @@ async def test_update_session_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2601,23 +2770,27 @@ async def test_update_session_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_session_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_session_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_session_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2626,7 +2799,7 @@ async def test_update_session_entity_type_async(
request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest,
):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2701,7 +2874,7 @@ def test_update_session_entity_type_field_headers():
@pytest.mark.asyncio
async def test_update_session_entity_type_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2784,7 +2957,7 @@ def test_update_session_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_update_session_entity_type_flattened_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2821,7 +2994,7 @@ async def test_update_session_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_update_session_entity_type_flattened_error_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2871,6 +3044,27 @@ def test_delete_session_entity_type(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_session_entity_type_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 = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_session_entity_type), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest()
+
+
def test_delete_session_entity_type_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2941,6 +3135,27 @@ def test_delete_session_entity_type_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_session_entity_type_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_session_entity_type), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_session_entity_type()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest()
+
+
@pytest.mark.asyncio
async def test_delete_session_entity_type_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2949,7 +3164,7 @@ async def test_delete_session_entity_type_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2964,23 +3179,27 @@ async def test_delete_session_entity_type_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_session_entity_type
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_session_entity_type(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_session_entity_type(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2989,7 +3208,7 @@ async def test_delete_session_entity_type_async(
request_type=session_entity_type.DeleteSessionEntityTypeRequest,
):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3054,7 +3273,7 @@ def test_delete_session_entity_type_field_headers():
@pytest.mark.asyncio
async def test_delete_session_entity_type_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3126,7 +3345,7 @@ def test_delete_session_entity_type_flattened_error():
@pytest.mark.asyncio
async def test_delete_session_entity_type_flattened_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3155,7 +3374,7 @@ async def test_delete_session_entity_type_flattened_async():
@pytest.mark.asyncio
async def test_delete_session_entity_type_flattened_error_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3167,8 +3386,52 @@ async def test_delete_session_entity_type_flattened_error_async():
)
-def test_list_session_entity_types_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session_entity_type.ListSessionEntityTypesRequest,
+ dict,
+ ],
+)
+def test_list_session_entity_types_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session_entity_type.ListSessionEntityTypesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session_entity_type.ListSessionEntityTypesResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_session_entity_types(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListSessionEntityTypesPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_session_entity_types_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = SessionEntityTypesClient(
@@ -3308,6 +3571,92 @@ def test_list_session_entity_types_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_session_entity_types_rest_interceptors(null_interceptor):
+ transport = transports.SessionEntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SessionEntityTypesRestInterceptor(),
+ )
+ client = SessionEntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "post_list_session_entity_types"
+ ) as post, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "pre_list_session_entity_types"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session_entity_type.ListSessionEntityTypesRequest.pb(
+ session_entity_type.ListSessionEntityTypesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ session_entity_type.ListSessionEntityTypesResponse.to_json(
+ session_entity_type.ListSessionEntityTypesResponse()
+ )
+ )
+
+ request = session_entity_type.ListSessionEntityTypesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session_entity_type.ListSessionEntityTypesResponse()
+
+ client.list_session_entity_types(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_session_entity_types_rest_bad_request(
+ transport: str = "rest",
+ request_type=session_entity_type.ListSessionEntityTypesRequest,
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_session_entity_types(request)
+
+
def test_list_session_entity_types_rest_flattened():
client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3437,6 +3786,53 @@ def test_list_session_entity_types_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session_entity_type.GetSessionEntityTypeRequest,
+ dict,
+ ],
+)
+def test_get_session_entity_type_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session_entity_type.SessionEntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_session_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session_entity_type.SessionEntityType)
+ assert response.name == "name_value"
+ assert (
+ response.entity_override_mode
+ == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
+ )
+
+
def test_get_session_entity_type_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3561,6 +3957,90 @@ def test_get_session_entity_type_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_session_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.SessionEntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SessionEntityTypesRestInterceptor(),
+ )
+ client = SessionEntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "post_get_session_entity_type"
+ ) as post, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "pre_get_session_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session_entity_type.GetSessionEntityTypeRequest.pb(
+ session_entity_type.GetSessionEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session_entity_type.SessionEntityType.to_json(
+ session_entity_type.SessionEntityType()
+ )
+
+ request = session_entity_type.GetSessionEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session_entity_type.SessionEntityType()
+
+ client.get_session_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_session_entity_type_rest_bad_request(
+ transport: str = "rest",
+ request_type=session_entity_type.GetSessionEntityTypeRequest,
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_session_entity_type(request)
+
+
def test_get_session_entity_type_rest_flattened():
client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3620,11 +4100,140 @@ def test_get_session_entity_type_rest_flattened_error(transport: str = "rest"):
)
-def test_create_session_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionEntityTypesClient(
+def test_get_session_entity_type_rest_error():
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_session_entity_type.CreateSessionEntityTypeRequest,
+ dict,
+ ],
+)
+def test_create_session_entity_type_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request_init["session_entity_type"] = {
+ "name": "name_value",
+ "entity_override_mode": 1,
+ "entities": [
+ {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
+ ],
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_session_entity_type.CreateSessionEntityTypeRequest.meta.fields[
+ "session_entity_type"
+ ]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["session_entity_type"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["session_entity_type"][field])):
+ del request_init["session_entity_type"][field][i][subfield]
+ else:
+ del request_init["session_entity_type"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_session_entity_type.SessionEntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_session_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_session_entity_type.SessionEntityType)
+ assert response.name == "name_value"
+ assert (
+ response.entity_override_mode
+ == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
+ )
+
+
+def test_create_session_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
@@ -3753,6 +4362,90 @@ def test_create_session_entity_type_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_session_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.SessionEntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SessionEntityTypesRestInterceptor(),
+ )
+ client = SessionEntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "post_create_session_entity_type"
+ ) as post, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "pre_create_session_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_session_entity_type.CreateSessionEntityTypeRequest.pb(
+ gcdc_session_entity_type.CreateSessionEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_session_entity_type.SessionEntityType.to_json(
+ gcdc_session_entity_type.SessionEntityType()
+ )
+
+ request = gcdc_session_entity_type.CreateSessionEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_session_entity_type.SessionEntityType()
+
+ client.create_session_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_session_entity_type_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest,
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_session_entity_type(request)
+
+
def test_create_session_entity_type_rest_flattened():
client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3818,39 +4511,170 @@ def test_create_session_entity_type_rest_flattened_error(transport: str = "rest"
)
-def test_update_session_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.update_session_entity_type
- in client._transport._wrapped_methods
- )
+def test_create_session_entity_type_rest_error():
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.update_session_entity_type
- ] = mock_rpc
- request = {}
- client.update_session_entity_type(request)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_session_entity_type.UpdateSessionEntityTypeRequest,
+ dict,
+ ],
+)
+def test_update_session_entity_type_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session_entity_type": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ }
+ request_init["session_entity_type"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5",
+ "entity_override_mode": 1,
+ "entities": [
+ {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
+ ],
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_session_entity_type.UpdateSessionEntityTypeRequest.meta.fields[
+ "session_entity_type"
+ ]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["session_entity_type"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["session_entity_type"][field])):
+ del request_init["session_entity_type"][field][i][subfield]
+ else:
+ del request_init["session_entity_type"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_session_entity_type.SessionEntityType(
+ name="name_value",
+ entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_session_entity_type.SessionEntityType.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_session_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_session_entity_type.SessionEntityType)
+ assert response.name == "name_value"
+ assert (
+ response.entity_override_mode
+ == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
+ )
+
+
+def test_update_session_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_session_entity_type
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_session_entity_type
+ ] = mock_rpc
+
+ request = {}
+ client.update_session_entity_type(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
client.update_session_entity_type(request)
@@ -3940,6 +4764,92 @@ def test_update_session_entity_type_rest_unset_required_fields():
assert set(unset_fields) == (set(("updateMask",)) & set(("sessionEntityType",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_session_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.SessionEntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SessionEntityTypesRestInterceptor(),
+ )
+ client = SessionEntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "post_update_session_entity_type"
+ ) as post, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "pre_update_session_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_session_entity_type.UpdateSessionEntityTypeRequest.pb(
+ gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_session_entity_type.SessionEntityType.to_json(
+ gcdc_session_entity_type.SessionEntityType()
+ )
+
+ request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_session_entity_type.SessionEntityType()
+
+ client.update_session_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_session_entity_type_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest,
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session_entity_type": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_session_entity_type(request)
+
+
def test_update_session_entity_type_rest_flattened():
client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4007,33 +4917,76 @@ def test_update_session_entity_type_rest_flattened_error(transport: str = "rest"
)
-def test_delete_session_entity_type_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.delete_session_entity_type
- in client._transport._wrapped_methods
- )
+def test_update_session_entity_type_rest_error():
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.delete_session_entity_type
- ] = mock_rpc
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session_entity_type.DeleteSessionEntityTypeRequest,
+ dict,
+ ],
+)
+def test_delete_session_entity_type_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_session_entity_type(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_session_entity_type_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.delete_session_entity_type
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.delete_session_entity_type
+ ] = mock_rpc
request = {}
client.delete_session_entity_type(request)
@@ -4128,6 +5081,82 @@ def test_delete_session_entity_type_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_session_entity_type_rest_interceptors(null_interceptor):
+ transport = transports.SessionEntityTypesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.SessionEntityTypesRestInterceptor(),
+ )
+ client = SessionEntityTypesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionEntityTypesRestInterceptor, "pre_delete_session_entity_type"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = session_entity_type.DeleteSessionEntityTypeRequest.pb(
+ session_entity_type.DeleteSessionEntityTypeRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = session_entity_type.DeleteSessionEntityTypeRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_session_entity_type(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_session_entity_type_rest_bad_request(
+ transport: str = "rest",
+ request_type=session_entity_type.DeleteSessionEntityTypeRequest,
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_session_entity_type(request)
+
+
def test_delete_session_entity_type_rest_flattened():
client = SessionEntityTypesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4185,6 +5214,12 @@ def test_delete_session_entity_type_rest_flattened_error(transport: str = "rest"
)
+def test_delete_session_entity_type_rest_error():
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.SessionEntityTypesGrpcTransport(
@@ -4271,1498 +5306,24 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = SessionEntityTypesClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_session_entity_types_empty_call_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_session_entity_types), "__call__"
- ) as call:
- call.return_value = session_entity_type.ListSessionEntityTypesResponse()
- client.list_session_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.ListSessionEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_session_entity_type_empty_call_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_session_entity_type), "__call__"
- ) as call:
- call.return_value = session_entity_type.SessionEntityType()
- client.get_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.GetSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_session_entity_type_empty_call_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_session_entity_type), "__call__"
- ) as call:
- call.return_value = gcdc_session_entity_type.SessionEntityType()
- client.create_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.CreateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_session_entity_type_empty_call_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_session_entity_type), "__call__"
- ) as call:
- call.return_value = gcdc_session_entity_type.SessionEntityType()
- client.update_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_session_entity_type_empty_call_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_session_entity_type), "__call__"
- ) as call:
- call.return_value = None
- client.delete_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.DeleteSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = SessionEntityTypesAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_session_entity_types_empty_call_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_session_entity_types), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session_entity_type.ListSessionEntityTypesResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_session_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.ListSessionEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_session_entity_type_empty_call_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_session_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
- )
- await client.get_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.GetSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_session_entity_type_empty_call_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_session_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
- )
- await client.create_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.CreateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_session_entity_type_empty_call_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_session_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
- )
- await client.update_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_session_entity_type_empty_call_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_session_entity_type), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.DeleteSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = SessionEntityTypesClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_session_entity_types_rest_bad_request(
- request_type=session_entity_type.ListSessionEntityTypesRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_session_entity_types(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session_entity_type.ListSessionEntityTypesRequest,
- dict,
- ],
-)
-def test_list_session_entity_types_rest_call_success(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session_entity_type.ListSessionEntityTypesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session_entity_type.ListSessionEntityTypesResponse.pb(
- return_value
- )
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_session_entity_types(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListSessionEntityTypesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_session_entity_types_rest_interceptors(null_interceptor):
- transport = transports.SessionEntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SessionEntityTypesRestInterceptor(),
- )
- client = SessionEntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "post_list_session_entity_types"
- ) as post, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "pre_list_session_entity_types"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session_entity_type.ListSessionEntityTypesRequest.pb(
- session_entity_type.ListSessionEntityTypesRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session_entity_type.ListSessionEntityTypesResponse.to_json(
- session_entity_type.ListSessionEntityTypesResponse()
- )
- req.return_value.content = return_value
-
- request = session_entity_type.ListSessionEntityTypesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session_entity_type.ListSessionEntityTypesResponse()
-
- client.list_session_entity_types(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_session_entity_type_rest_bad_request(
- request_type=session_entity_type.GetSessionEntityTypeRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_session_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session_entity_type.GetSessionEntityTypeRequest,
- dict,
- ],
-)
-def test_get_session_entity_type_rest_call_success(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session_entity_type.SessionEntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_session_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session_entity_type.SessionEntityType)
- assert response.name == "name_value"
- assert (
- response.entity_override_mode
- == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_session_entity_type_rest_interceptors(null_interceptor):
- transport = transports.SessionEntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SessionEntityTypesRestInterceptor(),
- )
- client = SessionEntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "post_get_session_entity_type"
- ) as post, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "pre_get_session_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session_entity_type.GetSessionEntityTypeRequest.pb(
- session_entity_type.GetSessionEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session_entity_type.SessionEntityType.to_json(
- session_entity_type.SessionEntityType()
- )
- req.return_value.content = return_value
-
- request = session_entity_type.GetSessionEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session_entity_type.SessionEntityType()
-
- client.get_session_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_session_entity_type_rest_bad_request(
- request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_session_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_session_entity_type.CreateSessionEntityTypeRequest,
- dict,
- ],
-)
-def test_create_session_entity_type_rest_call_success(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request_init["session_entity_type"] = {
- "name": "name_value",
- "entity_override_mode": 1,
- "entities": [
- {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
- ],
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_session_entity_type.CreateSessionEntityTypeRequest.meta.fields[
- "session_entity_type"
- ]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["session_entity_type"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["session_entity_type"][field])):
- del request_init["session_entity_type"][field][i][subfield]
- else:
- del request_init["session_entity_type"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_session_entity_type.SessionEntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_session_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_session_entity_type.SessionEntityType)
- assert response.name == "name_value"
- assert (
- response.entity_override_mode
- == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_session_entity_type_rest_interceptors(null_interceptor):
- transport = transports.SessionEntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SessionEntityTypesRestInterceptor(),
- )
- client = SessionEntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "post_create_session_entity_type"
- ) as post, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "pre_create_session_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_session_entity_type.CreateSessionEntityTypeRequest.pb(
- gcdc_session_entity_type.CreateSessionEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_session_entity_type.SessionEntityType.to_json(
- gcdc_session_entity_type.SessionEntityType()
- )
- req.return_value.content = return_value
-
- request = gcdc_session_entity_type.CreateSessionEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_session_entity_type.SessionEntityType()
-
- client.create_session_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_session_entity_type_rest_bad_request(
- request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "session_entity_type": {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_session_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_session_entity_type.UpdateSessionEntityTypeRequest,
- dict,
- ],
-)
-def test_update_session_entity_type_rest_call_success(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "session_entity_type": {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- }
- request_init["session_entity_type"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5",
- "entity_override_mode": 1,
- "entities": [
- {"value": "value_value", "synonyms": ["synonyms_value1", "synonyms_value2"]}
- ],
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_session_entity_type.UpdateSessionEntityTypeRequest.meta.fields[
- "session_entity_type"
- ]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["session_entity_type"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["session_entity_type"][field])):
- del request_init["session_entity_type"][field][i][subfield]
- else:
- del request_init["session_entity_type"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_session_entity_type.SessionEntityType(
- name="name_value",
- entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_session_entity_type.SessionEntityType.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_session_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_session_entity_type.SessionEntityType)
- assert response.name == "name_value"
- assert (
- response.entity_override_mode
- == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_session_entity_type_rest_interceptors(null_interceptor):
- transport = transports.SessionEntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SessionEntityTypesRestInterceptor(),
- )
- client = SessionEntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "post_update_session_entity_type"
- ) as post, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "pre_update_session_entity_type"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_session_entity_type.UpdateSessionEntityTypeRequest.pb(
- gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_session_entity_type.SessionEntityType.to_json(
- gcdc_session_entity_type.SessionEntityType()
- )
- req.return_value.content = return_value
-
- request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_session_entity_type.SessionEntityType()
-
- client.update_session_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_session_entity_type_rest_bad_request(
- request_type=session_entity_type.DeleteSessionEntityTypeRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_session_entity_type(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session_entity_type.DeleteSessionEntityTypeRequest,
- dict,
- ],
-)
-def test_delete_session_entity_type_rest_call_success(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4/entityTypes/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_session_entity_type(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_session_entity_type_rest_interceptors(null_interceptor):
- transport = transports.SessionEntityTypesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.SessionEntityTypesRestInterceptor(),
- )
- client = SessionEntityTypesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionEntityTypesRestInterceptor, "pre_delete_session_entity_type"
- ) as pre:
- pre.assert_not_called()
- pb_message = session_entity_type.DeleteSessionEntityTypeRequest.pb(
- session_entity_type.DeleteSessionEntityTypeRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = session_entity_type.DeleteSessionEntityTypeRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_session_entity_type(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_session_entity_types_empty_call_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_session_entity_types), "__call__"
- ) as call:
- client.list_session_entity_types(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.ListSessionEntityTypesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_session_entity_type_empty_call_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_session_entity_type), "__call__"
- ) as call:
- client.get_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.GetSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_session_entity_type_empty_call_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_session_entity_type), "__call__"
- ) as call:
- client.create_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.CreateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_session_entity_type_empty_call_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_session_entity_type), "__call__"
- ) as call:
- client.update_session_entity_type(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_session_entity_type.UpdateSessionEntityTypeRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_session_entity_type_empty_call_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_session_entity_type), "__call__"
- ) as call:
- client.delete_session_entity_type(request=None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session_entity_type.DeleteSessionEntityTypeRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = SessionEntityTypesClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6277,110 +5838,410 @@ def test_parse_common_billing_account_path():
assert expected == actual
-def test_common_folder_path():
- folder = "squid"
- expected = "folders/{folder}".format(
- folder=folder,
+def test_common_folder_path():
+ folder = "squid"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = SessionEntityTypesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "clam",
+ }
+ path = SessionEntityTypesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionEntityTypesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "whelk"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = SessionEntityTypesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "octopus",
+ }
+ path = SessionEntityTypesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionEntityTypesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "oyster"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = SessionEntityTypesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nudibranch",
+ }
+ path = SessionEntityTypesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionEntityTypesClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "cuttlefish"
+ location = "mussel"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = SessionEntityTypesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "winkle",
+ "location": "nautilus",
+ }
+ path = SessionEntityTypesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionEntityTypesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.SessionEntityTypesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.SessionEntityTypesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = SessionEntityTypesClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SessionEntityTypesClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "clam",
- }
- path = SessionEntityTypesClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SessionEntityTypesClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "whelk"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = SessionEntityTypesClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "octopus",
- }
- path = SessionEntityTypesClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = SessionEntityTypesClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "oyster"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SessionEntityTypesClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "nudibranch",
- }
- path = SessionEntityTypesClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SessionEntityTypesClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "cuttlefish"
- location = "mussel"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = SessionEntityTypesClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "winkle",
- "location": "nautilus",
- }
- path = SessionEntityTypesClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = SessionEntityTypesClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.SessionEntityTypesTransport, "_prep_wrapped_messages"
- ) as prep:
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.SessionEntityTypesTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = SessionEntityTypesClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6410,7 +6271,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6463,7 +6324,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6508,7 +6369,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6549,7 +6410,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6604,7 +6465,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6651,7 +6512,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6694,7 +6555,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6749,7 +6610,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6796,7 +6657,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -6839,7 +6700,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6894,7 +6755,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6941,7 +6802,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6984,7 +6845,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7036,7 +6897,9 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = SessionEntityTypesAsyncClient(credentials=async_anonymous_credentials())
+ client = SessionEntityTypesAsyncClient(
+ credentials=ga_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.
@@ -7082,7 +6945,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7098,41 +6961,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = SessionEntityTypesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = SessionEntityTypesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = SessionEntityTypesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py
index 2af3104ad918..45b17af9d887 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -55,8 +37,16 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.type import latlng_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.sessions import (
SessionsAsyncClient,
@@ -75,24 +65,10 @@
)
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1143,6 +1119,25 @@ def test_detect_intent(request_type, transport: str = "grpc"):
assert response.allow_cancellation is True
+def test_detect_intent_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 = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.detect_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.detect_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.DetectIntentRequest()
+
+
def test_detect_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1206,6 +1201,32 @@ def test_detect_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_detect_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.detect_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session.DetectIntentResponse(
+ response_id="response_id_value",
+ output_audio=b"output_audio_blob",
+ response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
+ allow_cancellation=True,
+ )
+ )
+ response = await client.detect_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.DetectIntentRequest()
+
+
@pytest.mark.asyncio
async def test_detect_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1214,7 +1235,7 @@ async def test_detect_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1229,23 +1250,27 @@ async def test_detect_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.detect_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.detect_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.detect_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1253,7 +1278,7 @@ async def test_detect_intent_async(
transport: str = "grpc_asyncio", request_type=session.DetectIntentRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1325,7 +1350,7 @@ def test_detect_intent_field_headers():
@pytest.mark.asyncio
async def test_detect_intent_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1390,6 +1415,27 @@ def test_server_streaming_detect_intent(request_type, transport: str = "grpc"):
assert isinstance(message, session.DetectIntentResponse)
+def test_server_streaming_detect_intent_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 = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.server_streaming_detect_intent), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.server_streaming_detect_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.DetectIntentRequest()
+
+
def test_server_streaming_detect_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1460,6 +1506,30 @@ def test_server_streaming_detect_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_server_streaming_detect_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.server_streaming_detect_intent), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
+ call.return_value.read = mock.AsyncMock(
+ side_effect=[session.DetectIntentResponse()]
+ )
+ response = await client.server_streaming_detect_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.DetectIntentRequest()
+
+
@pytest.mark.asyncio
async def test_server_streaming_detect_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1468,7 +1538,7 @@ async def test_server_streaming_detect_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1483,23 +1553,27 @@ async def test_server_streaming_detect_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.server_streaming_detect_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.server_streaming_detect_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.server_streaming_detect_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1507,7 +1581,7 @@ async def test_server_streaming_detect_intent_async(
transport: str = "grpc_asyncio", request_type=session.DetectIntentRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1576,7 +1650,7 @@ def test_server_streaming_detect_intent_field_headers():
@pytest.mark.asyncio
async def test_server_streaming_detect_intent_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1692,7 +1766,7 @@ async def test_streaming_detect_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1707,23 +1781,27 @@ async def test_streaming_detect_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.streaming_detect_intent
- ] = mock_rpc
+ ] = mock_object
request = [{}]
await client.streaming_detect_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.streaming_detect_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1731,7 +1809,7 @@ async def test_streaming_detect_intent_async(
transport: str = "grpc_asyncio", request_type=session.StreamingDetectIntentRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1801,6 +1879,25 @@ def test_match_intent(request_type, transport: str = "grpc"):
assert isinstance(response, session.MatchIntentResponse)
+def test_match_intent_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 = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.match_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.match_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.MatchIntentRequest()
+
+
def test_match_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1864,6 +1961,27 @@ def test_match_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_match_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.match_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session.MatchIntentResponse()
+ )
+ response = await client.match_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.MatchIntentRequest()
+
+
@pytest.mark.asyncio
async def test_match_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1872,7 +1990,7 @@ async def test_match_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1887,23 +2005,27 @@ async def test_match_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.match_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.match_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.match_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1911,7 +2033,7 @@ async def test_match_intent_async(
transport: str = "grpc_asyncio", request_type=session.MatchIntentRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1974,7 +2096,7 @@ def test_match_intent_field_headers():
@pytest.mark.asyncio
async def test_match_intent_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2041,6 +2163,25 @@ def test_fulfill_intent(request_type, transport: str = "grpc"):
assert response.output_audio == b"output_audio_blob"
+def test_fulfill_intent_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 = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.fulfill_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.FulfillIntentRequest()
+
+
def test_fulfill_intent_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2100,6 +2241,30 @@ def test_fulfill_intent_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_fulfill_intent_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session.FulfillIntentResponse(
+ response_id="response_id_value",
+ output_audio=b"output_audio_blob",
+ )
+ )
+ response = await client.fulfill_intent()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.FulfillIntentRequest()
+
+
@pytest.mark.asyncio
async def test_fulfill_intent_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2108,7 +2273,7 @@ async def test_fulfill_intent_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2123,23 +2288,27 @@ async def test_fulfill_intent_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.fulfill_intent
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.fulfill_intent(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.fulfill_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2147,7 +2316,7 @@ async def test_fulfill_intent_async(
transport: str = "grpc_asyncio", request_type=session.FulfillIntentRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2215,7 +2384,7 @@ def test_fulfill_intent_field_headers():
@pytest.mark.asyncio
async def test_fulfill_intent_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2284,6 +2453,27 @@ def test_submit_answer_feedback(request_type, transport: str = "grpc"):
assert response.custom_rating == "custom_rating_value"
+def test_submit_answer_feedback_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 = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.submit_answer_feedback), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.submit_answer_feedback()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.SubmitAnswerFeedbackRequest()
+
+
def test_submit_answer_feedback_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2356,6 +2546,32 @@ def test_submit_answer_feedback_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_submit_answer_feedback_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.submit_answer_feedback), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ session.AnswerFeedback(
+ rating=session.AnswerFeedback.Rating.THUMBS_UP,
+ custom_rating="custom_rating_value",
+ )
+ )
+ response = await client.submit_answer_feedback()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == session.SubmitAnswerFeedbackRequest()
+
+
@pytest.mark.asyncio
async def test_submit_answer_feedback_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2364,7 +2580,7 @@ async def test_submit_answer_feedback_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2379,23 +2595,27 @@ async def test_submit_answer_feedback_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.submit_answer_feedback
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.submit_answer_feedback(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.submit_answer_feedback(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2403,7 +2623,7 @@ async def test_submit_answer_feedback_async(
transport: str = "grpc_asyncio", request_type=session.SubmitAnswerFeedbackRequest
):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2475,7 +2695,7 @@ def test_submit_answer_feedback_field_headers():
@pytest.mark.asyncio
async def test_submit_answer_feedback_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2506,24 +2726,72 @@ async def test_submit_answer_feedback_field_headers_async():
) in kw["metadata"]
-def test_detect_intent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.detect_intent in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session.DetectIntentRequest,
+ dict,
+ ],
+)
+def test_detect_intent_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session.DetectIntentResponse(
+ response_id="response_id_value",
+ output_audio=b"output_audio_blob",
+ response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
+ allow_cancellation=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session.DetectIntentResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.detect_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session.DetectIntentResponse)
+ assert response.response_id == "response_id_value"
+ assert response.output_audio == b"output_audio_blob"
+ assert response.response_type == session.DetectIntentResponse.ResponseType.PARTIAL
+ assert response.allow_cancellation is True
+
+
+def test_detect_intent_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.detect_intent in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
@@ -2632,6 +2900,146 @@ def test_detect_intent_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_detect_intent_rest_interceptors(null_interceptor):
+ transport = transports.SessionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
+ )
+ client = SessionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionsRestInterceptor, "post_detect_intent"
+ ) as post, mock.patch.object(
+ transports.SessionsRestInterceptor, "pre_detect_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session.DetectIntentRequest.pb(session.DetectIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session.DetectIntentResponse.to_json(
+ session.DetectIntentResponse()
+ )
+
+ request = session.DetectIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session.DetectIntentResponse()
+
+ client.detect_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_detect_intent_rest_bad_request(
+ transport: str = "rest", request_type=session.DetectIntentRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.detect_intent(request)
+
+
+def test_detect_intent_rest_error():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session.DetectIntentRequest,
+ dict,
+ ],
+)
+def test_server_streaming_detect_intent_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session.DetectIntentResponse(
+ response_id="response_id_value",
+ output_audio=b"output_audio_blob",
+ response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
+ allow_cancellation=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session.DetectIntentResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ json_return_value = "[{}]".format(json_return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ with mock.patch.object(response_value, "iter_content") as iter_content:
+ iter_content.return_value = iter(json_return_value)
+ response = client.server_streaming_detect_intent(request)
+
+ assert isinstance(response, Iterable)
+ response = next(response)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session.DetectIntentResponse)
+ assert response.response_id == "response_id_value"
+ assert response.output_audio == b"output_audio_blob"
+ assert response.response_type == session.DetectIntentResponse.ResponseType.PARTIAL
+ assert response.allow_cancellation is True
+
+
def test_server_streaming_detect_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2770,35 +3178,162 @@ def test_server_streaming_detect_intent_rest_unset_required_fields():
)
-def test_streaming_detect_intent_rest_no_http_options():
- client = SessionsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_server_streaming_detect_intent_rest_interceptors(null_interceptor):
+ transport = transports.SessionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
)
- request = session.StreamingDetectIntentRequest()
- requests = [request]
- with pytest.raises(RuntimeError):
- client.streaming_detect_intent(requests)
+ client = SessionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionsRestInterceptor, "post_server_streaming_detect_intent"
+ ) as post, mock.patch.object(
+ transports.SessionsRestInterceptor, "pre_server_streaming_detect_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session.DetectIntentRequest.pb(session.DetectIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session.DetectIntentResponse.to_json(
+ session.DetectIntentResponse()
+ )
+ req.return_value._content = "[{}]".format(req.return_value._content)
+ request = session.DetectIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session.DetectIntentResponse()
-def test_match_intent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ client.server_streaming_detect_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ pre.assert_called_once()
+ post.assert_called_once()
- # Ensure method has been cached
- assert client._transport.match_intent in client._transport._wrapped_methods
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
+def test_server_streaming_detect_intent_rest_bad_request(
+ transport: str = "rest", request_type=session.DetectIntentRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.server_streaming_detect_intent(request)
+
+
+def test_server_streaming_detect_intent_rest_error():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+def test_streaming_detect_intent_rest_no_http_options():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = session.StreamingDetectIntentRequest()
+ requests = [request]
+ with pytest.raises(RuntimeError):
+ client.streaming_detect_intent(requests)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session.MatchIntentRequest,
+ dict,
+ ],
+)
+def test_match_intent_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session.MatchIntentResponse(
+ text="text_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session.MatchIntentResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.match_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session.MatchIntentResponse)
+
+
+def test_match_intent_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.match_intent in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
@@ -2907,43 +3442,138 @@ def test_match_intent_rest_unset_required_fields():
)
-def test_fulfill_intent_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_match_intent_rest_interceptors(null_interceptor):
+ transport = transports.SessionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
+ )
+ client = SessionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionsRestInterceptor, "post_match_intent"
+ ) as post, mock.patch.object(
+ transports.SessionsRestInterceptor, "pre_match_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session.MatchIntentRequest.pb(session.MatchIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session.MatchIntentResponse.to_json(
+ session.MatchIntentResponse()
+ )
- # Ensure method has been cached
- assert client._transport.fulfill_intent in client._transport._wrapped_methods
+ request = session.MatchIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session.MatchIntentResponse()
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.match_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[client._transport.fulfill_intent] = mock_rpc
- request = {}
- client.fulfill_intent(request)
+ pre.assert_called_once()
+ post.assert_called_once()
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
- client.fulfill_intent(request)
+def test_match_intent_rest_bad_request(
+ transport: str = "rest", request_type=session.MatchIntentRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.match_intent(request)
-def test_submit_answer_feedback_rest_use_cached_wrapped_rpc():
+def test_match_intent_rest_error():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session.FulfillIntentRequest,
+ dict,
+ ],
+)
+def test_fulfill_intent_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "match_intent_request": {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session.FulfillIntentResponse(
+ response_id="response_id_value",
+ output_audio=b"output_audio_blob",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session.FulfillIntentResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.fulfill_intent(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session.FulfillIntentResponse)
+ assert response.response_id == "response_id_value"
+ assert response.output_audio == b"output_audio_blob"
+
+
+def test_fulfill_intent_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -2957,37 +3587,204 @@ def test_submit_answer_feedback_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert (
- client._transport.submit_answer_feedback
- in client._transport._wrapped_methods
- )
+ assert client._transport.fulfill_intent in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[
- client._transport.submit_answer_feedback
- ] = mock_rpc
+ client._transport._wrapped_methods[client._transport.fulfill_intent] = mock_rpc
request = {}
- client.submit_answer_feedback(request)
+ client.fulfill_intent(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.submit_answer_feedback(request)
+ client.fulfill_intent(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_submit_answer_feedback_rest_required_fields(
- request_type=session.SubmitAnswerFeedbackRequest,
-):
- transport_class = transports.SessionsRestTransport
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_fulfill_intent_rest_interceptors(null_interceptor):
+ transport = transports.SessionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
+ )
+ client = SessionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionsRestInterceptor, "post_fulfill_intent"
+ ) as post, mock.patch.object(
+ transports.SessionsRestInterceptor, "pre_fulfill_intent"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session.FulfillIntentRequest.pb(session.FulfillIntentRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session.FulfillIntentResponse.to_json(
+ session.FulfillIntentResponse()
+ )
+
+ request = session.FulfillIntentRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session.FulfillIntentResponse()
+
+ client.fulfill_intent(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_fulfill_intent_rest_bad_request(
+ transport: str = "rest", request_type=session.FulfillIntentRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "match_intent_request": {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.fulfill_intent(request)
+
+
+def test_fulfill_intent_rest_error():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ session.SubmitAnswerFeedbackRequest,
+ dict,
+ ],
+)
+def test_submit_answer_feedback_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = session.AnswerFeedback(
+ rating=session.AnswerFeedback.Rating.THUMBS_UP,
+ custom_rating="custom_rating_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = session.AnswerFeedback.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.submit_answer_feedback(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, session.AnswerFeedback)
+ assert response.rating == session.AnswerFeedback.Rating.THUMBS_UP
+ assert response.custom_rating == "custom_rating_value"
+
+
+def test_submit_answer_feedback_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.submit_answer_feedback
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.submit_answer_feedback
+ ] = mock_rpc
+
+ request = {}
+ client.submit_answer_feedback(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.submit_answer_feedback(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_submit_answer_feedback_rest_required_fields(
+ request_type=session.SubmitAnswerFeedbackRequest,
+):
+ transport_class = transports.SessionsRestTransport
request_init = {}
request_init["session"] = ""
@@ -3081,6 +3878,93 @@ def test_submit_answer_feedback_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_submit_answer_feedback_rest_interceptors(null_interceptor):
+ transport = transports.SessionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
+ )
+ client = SessionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.SessionsRestInterceptor, "post_submit_answer_feedback"
+ ) as post, mock.patch.object(
+ transports.SessionsRestInterceptor, "pre_submit_answer_feedback"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = session.SubmitAnswerFeedbackRequest.pb(
+ session.SubmitAnswerFeedbackRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = session.AnswerFeedback.to_json(
+ session.AnswerFeedback()
+ )
+
+ request = session.SubmitAnswerFeedbackRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = session.AnswerFeedback()
+
+ client.submit_answer_feedback(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_submit_answer_feedback_rest_bad_request(
+ transport: str = "rest", request_type=session.SubmitAnswerFeedbackRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.submit_answer_feedback(request)
+
+
+def test_submit_answer_feedback_rest_error():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_streaming_detect_intent_rest_error():
client = SessionsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
@@ -3186,1328 +4070,18 @@ def test_transport_adc(transport_class):
adc.assert_called_once()
-def test_transport_kind_grpc():
- transport = SessionsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_detect_intent_empty_call_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.detect_intent), "__call__") as call:
- call.return_value = session.DetectIntentResponse()
- client.detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_server_streaming_detect_intent_empty_call_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.server_streaming_detect_intent), "__call__"
- ) as call:
- call.return_value = iter([session.DetectIntentResponse()])
- client.server_streaming_detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_match_intent_empty_call_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.match_intent), "__call__") as call:
- call.return_value = session.MatchIntentResponse()
- client.match_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.MatchIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_fulfill_intent_empty_call_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call:
- call.return_value = session.FulfillIntentResponse()
- client.fulfill_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.FulfillIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_submit_answer_feedback_empty_call_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.submit_answer_feedback), "__call__"
- ) as call:
- call.return_value = session.AnswerFeedback()
- client.submit_answer_feedback(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.SubmitAnswerFeedbackRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = SessionsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_detect_intent_empty_call_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.detect_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session.DetectIntentResponse(
- response_id="response_id_value",
- output_audio=b"output_audio_blob",
- response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
- allow_cancellation=True,
- )
- )
- await client.detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_server_streaming_detect_intent_empty_call_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.server_streaming_detect_intent), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
- call.return_value.read = mock.AsyncMock(
- side_effect=[session.DetectIntentResponse()]
- )
- await client.server_streaming_detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_match_intent_empty_call_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.match_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session.MatchIntentResponse()
- )
- await client.match_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.MatchIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_fulfill_intent_empty_call_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session.FulfillIntentResponse(
- response_id="response_id_value",
- output_audio=b"output_audio_blob",
- )
- )
- await client.fulfill_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.FulfillIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_submit_answer_feedback_empty_call_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.submit_answer_feedback), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- session.AnswerFeedback(
- rating=session.AnswerFeedback.Rating.THUMBS_UP,
- custom_rating="custom_rating_value",
- )
- )
- await client.submit_answer_feedback(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.SubmitAnswerFeedbackRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = SessionsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_detect_intent_rest_bad_request(request_type=session.DetectIntentRequest):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.detect_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session.DetectIntentRequest,
- dict,
- ],
-)
-def test_detect_intent_rest_call_success(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session.DetectIntentResponse(
- response_id="response_id_value",
- output_audio=b"output_audio_blob",
- response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
- allow_cancellation=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session.DetectIntentResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.detect_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session.DetectIntentResponse)
- assert response.response_id == "response_id_value"
- assert response.output_audio == b"output_audio_blob"
- assert response.response_type == session.DetectIntentResponse.ResponseType.PARTIAL
- assert response.allow_cancellation is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_detect_intent_rest_interceptors(null_interceptor):
- transport = transports.SessionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
- )
- client = SessionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionsRestInterceptor, "post_detect_intent"
- ) as post, mock.patch.object(
- transports.SessionsRestInterceptor, "pre_detect_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session.DetectIntentRequest.pb(session.DetectIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session.DetectIntentResponse.to_json(
- session.DetectIntentResponse()
- )
- req.return_value.content = return_value
-
- request = session.DetectIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session.DetectIntentResponse()
-
- client.detect_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_server_streaming_detect_intent_rest_bad_request(
- request_type=session.DetectIntentRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.server_streaming_detect_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session.DetectIntentRequest,
- dict,
- ],
-)
-def test_server_streaming_detect_intent_rest_call_success(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session.DetectIntentResponse(
- response_id="response_id_value",
- output_audio=b"output_audio_blob",
- response_type=session.DetectIntentResponse.ResponseType.PARTIAL,
- allow_cancellation=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session.DetectIntentResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- json_return_value = "[{}]".format(json_return_value)
- response_value.iter_content = mock.Mock(return_value=iter(json_return_value))
- req.return_value = response_value
- response = client.server_streaming_detect_intent(request)
-
- assert isinstance(response, Iterable)
- response = next(response)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session.DetectIntentResponse)
- assert response.response_id == "response_id_value"
- assert response.output_audio == b"output_audio_blob"
- assert response.response_type == session.DetectIntentResponse.ResponseType.PARTIAL
- assert response.allow_cancellation is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_server_streaming_detect_intent_rest_interceptors(null_interceptor):
- transport = transports.SessionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
- )
- client = SessionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionsRestInterceptor, "post_server_streaming_detect_intent"
- ) as post, mock.patch.object(
- transports.SessionsRestInterceptor, "pre_server_streaming_detect_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session.DetectIntentRequest.pb(session.DetectIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session.DetectIntentResponse.to_json(
- session.DetectIntentResponse()
- )
- req.return_value.iter_content = mock.Mock(return_value=iter(return_value))
-
- request = session.DetectIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session.DetectIntentResponse()
-
- client.server_streaming_detect_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_streaming_detect_intent_rest_error():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- with pytest.raises(NotImplementedError) as not_implemented_error:
- client.streaming_detect_intent({})
- assert "Method StreamingDetectIntent is not available over REST transport" in str(
- not_implemented_error.value
- )
-
-
-def test_match_intent_rest_bad_request(request_type=session.MatchIntentRequest):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.match_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session.MatchIntentRequest,
- dict,
- ],
-)
-def test_match_intent_rest_call_success(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session.MatchIntentResponse(
- text="text_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session.MatchIntentResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.match_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session.MatchIntentResponse)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_match_intent_rest_interceptors(null_interceptor):
- transport = transports.SessionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
- )
- client = SessionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionsRestInterceptor, "post_match_intent"
- ) as post, mock.patch.object(
- transports.SessionsRestInterceptor, "pre_match_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session.MatchIntentRequest.pb(session.MatchIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session.MatchIntentResponse.to_json(
- session.MatchIntentResponse()
- )
- req.return_value.content = return_value
-
- request = session.MatchIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session.MatchIntentResponse()
-
- client.match_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_fulfill_intent_rest_bad_request(request_type=session.FulfillIntentRequest):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "match_intent_request": {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.fulfill_intent(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session.FulfillIntentRequest,
- dict,
- ],
-)
-def test_fulfill_intent_rest_call_success(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "match_intent_request": {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session.FulfillIntentResponse(
- response_id="response_id_value",
- output_audio=b"output_audio_blob",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session.FulfillIntentResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.fulfill_intent(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session.FulfillIntentResponse)
- assert response.response_id == "response_id_value"
- assert response.output_audio == b"output_audio_blob"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_fulfill_intent_rest_interceptors(null_interceptor):
- transport = transports.SessionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
- )
- client = SessionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionsRestInterceptor, "post_fulfill_intent"
- ) as post, mock.patch.object(
- transports.SessionsRestInterceptor, "pre_fulfill_intent"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session.FulfillIntentRequest.pb(session.FulfillIntentRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session.FulfillIntentResponse.to_json(
- session.FulfillIntentResponse()
- )
- req.return_value.content = return_value
-
- request = session.FulfillIntentRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session.FulfillIntentResponse()
-
- client.fulfill_intent(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_submit_answer_feedback_rest_bad_request(
- request_type=session.SubmitAnswerFeedbackRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.submit_answer_feedback(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- session.SubmitAnswerFeedbackRequest,
- dict,
- ],
-)
-def test_submit_answer_feedback_rest_call_success(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "session": "projects/sample1/locations/sample2/agents/sample3/sessions/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = session.AnswerFeedback(
- rating=session.AnswerFeedback.Rating.THUMBS_UP,
- custom_rating="custom_rating_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = session.AnswerFeedback.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.submit_answer_feedback(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, session.AnswerFeedback)
- assert response.rating == session.AnswerFeedback.Rating.THUMBS_UP
- assert response.custom_rating == "custom_rating_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_submit_answer_feedback_rest_interceptors(null_interceptor):
- transport = transports.SessionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.SessionsRestInterceptor(),
- )
- client = SessionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.SessionsRestInterceptor, "post_submit_answer_feedback"
- ) as post, mock.patch.object(
- transports.SessionsRestInterceptor, "pre_submit_answer_feedback"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = session.SubmitAnswerFeedbackRequest.pb(
- session.SubmitAnswerFeedbackRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = session.AnswerFeedback.to_json(session.AnswerFeedback())
- req.return_value.content = return_value
-
- request = session.SubmitAnswerFeedbackRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = session.AnswerFeedback()
-
- client.submit_answer_feedback(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
@pytest.mark.parametrize(
- "request_type",
+ "transport_name",
[
- operations_pb2.ListOperationsRequest,
- dict,
+ "grpc",
+ "rest",
],
)
-def test_list_operations_rest(request_type):
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_detect_intent_empty_call_rest():
- client = SessionsClient(
+def test_transport_kind(transport_name):
+ transport = SessionsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.detect_intent), "__call__") as call:
- client.detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_server_streaming_detect_intent_empty_call_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.server_streaming_detect_intent), "__call__"
- ) as call:
- client.server_streaming_detect_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.DetectIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_match_intent_empty_call_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.match_intent), "__call__") as call:
- client.match_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.MatchIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_fulfill_intent_empty_call_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call:
- client.fulfill_intent(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.FulfillIntentRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_submit_answer_feedback_empty_call_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.submit_answer_feedback), "__call__"
- ) as call:
- client.submit_answer_feedback(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = session.SubmitAnswerFeedbackRequest()
-
- assert args[0] == request_msg
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -5254,232 +4828,532 @@ def test_parse_tool_path():
"agent": "scallop",
"tool": "abalone",
}
- path = SessionsClient.tool_path(**expected)
+ path = SessionsClient.tool_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionsClient.parse_tool_path(path)
+ assert expected == actual
+
+
+def test_transition_route_group_path():
+ project = "squid"
+ location = "clam"
+ agent = "whelk"
+ flow = "octopus"
+ transition_route_group = "oyster"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ flow=flow,
+ transition_route_group=transition_route_group,
+ )
+ actual = SessionsClient.transition_route_group_path(
+ project, location, agent, flow, transition_route_group
+ )
+ assert expected == actual
+
+
+def test_parse_transition_route_group_path():
+ expected = {
+ "project": "nudibranch",
+ "location": "cuttlefish",
+ "agent": "mussel",
+ "flow": "winkle",
+ "transition_route_group": "nautilus",
+ }
+ path = SessionsClient.transition_route_group_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionsClient.parse_transition_route_group_path(path)
+ assert expected == actual
+
+
+def test_version_path():
+ project = "scallop"
+ location = "abalone"
+ agent = "squid"
+ flow = "clam"
+ version = "whelk"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ flow=flow,
+ version=version,
+ )
+ actual = SessionsClient.version_path(project, location, agent, flow, version)
+ assert expected == actual
+
+
+def test_parse_version_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "agent": "nudibranch",
+ "flow": "cuttlefish",
+ "version": "mussel",
+ }
+ path = SessionsClient.version_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionsClient.parse_version_path(path)
+ assert expected == actual
+
+
+def test_webhook_path():
+ project = "winkle"
+ location = "nautilus"
+ agent = "scallop"
+ webhook = "abalone"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ webhook=webhook,
+ )
+ actual = SessionsClient.webhook_path(project, location, agent, webhook)
+ assert expected == actual
+
+
+def test_parse_webhook_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ "agent": "whelk",
+ "webhook": "octopus",
+ }
+ path = SessionsClient.webhook_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionsClient.parse_webhook_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "oyster"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = SessionsClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nudibranch",
+ }
+ path = SessionsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = SessionsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = SessionsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = SessionsClient.common_folder_path(**expected)
# Check that the path construction is reversible.
- actual = SessionsClient.parse_tool_path(path)
+ actual = SessionsClient.parse_common_folder_path(path)
assert expected == actual
-def test_transition_route_group_path():
- project = "squid"
- location = "clam"
- agent = "whelk"
- flow = "octopus"
- transition_route_group = "oyster"
- expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
- project=project,
- location=location,
- agent=agent,
- flow=flow,
- transition_route_group=transition_route_group,
- )
- actual = SessionsClient.transition_route_group_path(
- project, location, agent, flow, transition_route_group
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
)
+ actual = SessionsClient.common_organization_path(organization)
assert expected == actual
-def test_parse_transition_route_group_path():
+def test_parse_common_organization_path():
expected = {
- "project": "nudibranch",
- "location": "cuttlefish",
- "agent": "mussel",
- "flow": "winkle",
- "transition_route_group": "nautilus",
+ "organization": "nautilus",
}
- path = SessionsClient.transition_route_group_path(**expected)
+ path = SessionsClient.common_organization_path(**expected)
# Check that the path construction is reversible.
- actual = SessionsClient.parse_transition_route_group_path(path)
+ actual = SessionsClient.parse_common_organization_path(path)
assert expected == actual
-def test_version_path():
+def test_common_project_path():
project = "scallop"
- location = "abalone"
- agent = "squid"
- flow = "clam"
- version = "whelk"
- expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(
+ expected = "projects/{project}".format(
project=project,
- location=location,
- agent=agent,
- flow=flow,
- version=version,
)
- actual = SessionsClient.version_path(project, location, agent, flow, version)
+ actual = SessionsClient.common_project_path(project)
assert expected == actual
-def test_parse_version_path():
+def test_parse_common_project_path():
expected = {
- "project": "octopus",
- "location": "oyster",
- "agent": "nudibranch",
- "flow": "cuttlefish",
- "version": "mussel",
+ "project": "abalone",
}
- path = SessionsClient.version_path(**expected)
+ path = SessionsClient.common_project_path(**expected)
# Check that the path construction is reversible.
- actual = SessionsClient.parse_version_path(path)
+ actual = SessionsClient.parse_common_project_path(path)
assert expected == actual
-def test_webhook_path():
- project = "winkle"
- location = "nautilus"
- agent = "scallop"
- webhook = "abalone"
- expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
project=project,
location=location,
- agent=agent,
- webhook=webhook,
)
- actual = SessionsClient.webhook_path(project, location, agent, webhook)
+ actual = SessionsClient.common_location_path(project, location)
assert expected == actual
-def test_parse_webhook_path():
+def test_parse_common_location_path():
expected = {
- "project": "squid",
- "location": "clam",
- "agent": "whelk",
- "webhook": "octopus",
+ "project": "whelk",
+ "location": "octopus",
}
- path = SessionsClient.webhook_path(**expected)
+ path = SessionsClient.common_location_path(**expected)
# Check that the path construction is reversible.
- actual = SessionsClient.parse_webhook_path(path)
+ actual = SessionsClient.parse_common_location_path(path)
assert expected == actual
-def test_common_billing_account_path():
- billing_account = "oyster"
- expected = "billingAccounts/{billing_account}".format(
- billing_account=billing_account,
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.SessionsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.SessionsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = SessionsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = SessionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SessionsClient.common_billing_account_path(billing_account)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "nudibranch",
- }
- path = SessionsClient.common_billing_account_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SessionsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
- )
- actual = SessionsClient.common_folder_path(folder)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = SessionsClient.common_folder_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = SessionsClient.parse_common_folder_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SessionsClient.common_organization_path(organization)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = SessionsClient.common_organization_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = SessionsClient.parse_common_organization_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
- )
- actual = SessionsClient.common_project_path(project)
- assert expected == actual
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = SessionsClient.common_project_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Check that the path construction is reversible.
- actual = SessionsClient.parse_common_project_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = SessionsClient.common_location_path(project, location)
- assert expected == actual
-
-
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = SessionsClient.common_location_path(**expected)
-
- # Check that the path construction is reversible.
- actual = SessionsClient.parse_common_location_path(path)
- assert expected == actual
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.SessionsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
- with mock.patch.object(
- transports.SessionsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = SessionsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -5509,7 +5383,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5562,7 +5436,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5607,7 +5481,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -5648,7 +5522,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5703,7 +5577,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5750,7 +5624,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -5793,7 +5667,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5848,7 +5722,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5895,7 +5769,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -5938,7 +5812,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5993,7 +5867,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6040,7 +5914,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6083,7 +5957,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6135,7 +6009,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = SessionsAsyncClient(credentials=async_anonymous_credentials())
+ client = SessionsAsyncClient(credentials=ga_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.
@@ -6181,7 +6055,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6197,41 +6071,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = SessionsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = SessionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = SessionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py
index 07ee09351c10..d0eeec7dbdd0 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -65,9 +47,17 @@
from google.protobuf import any_pb2 # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.rpc import status_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.test_cases import (
TestCasesAsyncClient,
@@ -91,24 +81,10 @@
from google.cloud.dialogflowcx_v3beta1.types import tool_call
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1166,6 +1142,25 @@ def test_list_test_cases(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_test_cases_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ListTestCasesRequest()
+
+
def test_list_test_cases_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1231,6 +1226,29 @@ def test_list_test_cases_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_test_cases_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ test_case.ListTestCasesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ListTestCasesRequest()
+
+
@pytest.mark.asyncio
async def test_list_test_cases_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1239,7 +1257,7 @@ async def test_list_test_cases_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1254,23 +1272,27 @@ async def test_list_test_cases_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_test_cases
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_test_cases(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_test_cases(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1278,7 +1300,7 @@ async def test_list_test_cases_async(
transport: str = "grpc_asyncio", request_type=test_case.ListTestCasesRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1344,7 +1366,7 @@ def test_list_test_cases_field_headers():
@pytest.mark.asyncio
async def test_list_test_cases_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1414,7 +1436,7 @@ def test_list_test_cases_flattened_error():
@pytest.mark.asyncio
async def test_list_test_cases_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1443,7 +1465,7 @@ async def test_list_test_cases_flattened_async():
@pytest.mark.asyncio
async def test_list_test_cases_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1493,16 +1515,12 @@ def test_list_test_cases_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_test_cases(request={}, retry=retry, timeout=timeout)
+ pager = client.list_test_cases(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1553,7 +1571,7 @@ def test_list_test_cases_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_test_cases_async_pager():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1603,7 +1621,7 @@ async def test_list_test_cases_async_pager():
@pytest.mark.asyncio
async def test_list_test_cases_async_pages():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1684,6 +1702,27 @@ def test_batch_delete_test_cases(request_type, transport: str = "grpc"):
assert response is None
+def test_batch_delete_test_cases_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_delete_test_cases), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.batch_delete_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.BatchDeleteTestCasesRequest()
+
+
def test_batch_delete_test_cases_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1754,6 +1793,27 @@ def test_batch_delete_test_cases_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_batch_delete_test_cases_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_delete_test_cases), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.batch_delete_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.BatchDeleteTestCasesRequest()
+
+
@pytest.mark.asyncio
async def test_batch_delete_test_cases_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1762,7 +1822,7 @@ async def test_batch_delete_test_cases_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1777,23 +1837,27 @@ async def test_batch_delete_test_cases_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.batch_delete_test_cases
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.batch_delete_test_cases(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.batch_delete_test_cases(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1801,7 +1865,7 @@ async def test_batch_delete_test_cases_async(
transport: str = "grpc_asyncio", request_type=test_case.BatchDeleteTestCasesRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1866,7 +1930,7 @@ def test_batch_delete_test_cases_field_headers():
@pytest.mark.asyncio
async def test_batch_delete_test_cases_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1938,7 +2002,7 @@ def test_batch_delete_test_cases_flattened_error():
@pytest.mark.asyncio
async def test_batch_delete_test_cases_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1967,7 +2031,7 @@ async def test_batch_delete_test_cases_flattened_async():
@pytest.mark.asyncio
async def test_batch_delete_test_cases_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2021,6 +2085,25 @@ def test_get_test_case(request_type, transport: str = "grpc"):
assert response.notes == "notes_value"
+def test_get_test_case_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_test_case), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.GetTestCaseRequest()
+
+
def test_get_test_case_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2084,6 +2167,32 @@ def test_get_test_case_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_test_case_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_test_case), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+ )
+ response = await client.get_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.GetTestCaseRequest()
+
+
@pytest.mark.asyncio
async def test_get_test_case_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2092,7 +2201,7 @@ async def test_get_test_case_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2107,23 +2216,27 @@ async def test_get_test_case_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_test_case
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_test_case(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_test_case(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2131,7 +2244,7 @@ async def test_get_test_case_async(
transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2203,7 +2316,7 @@ def test_get_test_case_field_headers():
@pytest.mark.asyncio
async def test_get_test_case_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2271,7 +2384,7 @@ def test_get_test_case_flattened_error():
@pytest.mark.asyncio
async def test_get_test_case_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2298,7 +2411,7 @@ async def test_get_test_case_flattened_async():
@pytest.mark.asyncio
async def test_get_test_case_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2352,6 +2465,25 @@ def test_create_test_case(request_type, transport: str = "grpc"):
assert response.notes == "notes_value"
+def test_create_test_case_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_test_case), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_test_case.CreateTestCaseRequest()
+
+
def test_create_test_case_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2417,6 +2549,32 @@ def test_create_test_case_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_test_case_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_test_case), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+ )
+ response = await client.create_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_test_case.CreateTestCaseRequest()
+
+
@pytest.mark.asyncio
async def test_create_test_case_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2425,7 +2583,7 @@ async def test_create_test_case_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2440,23 +2598,27 @@ async def test_create_test_case_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_test_case
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_test_case(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_test_case(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2464,7 +2626,7 @@ async def test_create_test_case_async(
transport: str = "grpc_asyncio", request_type=gcdc_test_case.CreateTestCaseRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2536,7 +2698,7 @@ def test_create_test_case_field_headers():
@pytest.mark.asyncio
async def test_create_test_case_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2611,7 +2773,7 @@ def test_create_test_case_flattened_error():
@pytest.mark.asyncio
async def test_create_test_case_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2644,7 +2806,7 @@ async def test_create_test_case_flattened_async():
@pytest.mark.asyncio
async def test_create_test_case_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2699,6 +2861,25 @@ def test_update_test_case(request_type, transport: str = "grpc"):
assert response.notes == "notes_value"
+def test_update_test_case_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_test_case), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_test_case.UpdateTestCaseRequest()
+
+
def test_update_test_case_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2760,6 +2941,32 @@ def test_update_test_case_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_test_case_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_test_case), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+ )
+ response = await client.update_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_test_case.UpdateTestCaseRequest()
+
+
@pytest.mark.asyncio
async def test_update_test_case_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2768,7 +2975,7 @@ async def test_update_test_case_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2783,23 +2990,27 @@ async def test_update_test_case_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_test_case
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_test_case(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_test_case(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2807,7 +3018,7 @@ async def test_update_test_case_async(
transport: str = "grpc_asyncio", request_type=gcdc_test_case.UpdateTestCaseRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2879,7 +3090,7 @@ def test_update_test_case_field_headers():
@pytest.mark.asyncio
async def test_update_test_case_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2954,7 +3165,7 @@ def test_update_test_case_flattened_error():
@pytest.mark.asyncio
async def test_update_test_case_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2987,7 +3198,7 @@ async def test_update_test_case_flattened_async():
@pytest.mark.asyncio
async def test_update_test_case_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3033,31 +3244,50 @@ def test_run_test_case(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
-def test_run_test_case_non_empty_request_with_auto_populated_field():
- # This test is a coverage failsafe to make sure that UUID4 fields are
- # automatically populated, according to AIP-4235, with non-empty requests.
+def test_run_test_case_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 = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
- # Populate all string fields in the request which are not UUID4
- # since we want to check that UUID4 are populated automatically
- # if they meet the requirements of AIP 4235.
- request = test_case.RunTestCaseRequest(
- name="name_value",
- environment="environment_value",
- )
-
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.run_test_case), "__call__") as call:
call.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client.run_test_case(request=request)
+ client.run_test_case()
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == test_case.RunTestCaseRequest(
+ assert args[0] == test_case.RunTestCaseRequest()
+
+
+def test_run_test_case_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = test_case.RunTestCaseRequest(
+ name="name_value",
+ environment="environment_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.run_test_case), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.run_test_case(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.RunTestCaseRequest(
name="name_value",
environment="environment_value",
)
@@ -3091,9 +3321,8 @@ def test_run_test_case_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.run_test_case(request)
@@ -3103,6 +3332,27 @@ def test_run_test_case_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_run_test_case_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.run_test_case), "__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.run_test_case()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.RunTestCaseRequest()
+
+
@pytest.mark.asyncio
async def test_run_test_case_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3111,7 +3361,7 @@ async def test_run_test_case_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3126,28 +3376,31 @@ async def test_run_test_case_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.run_test_case
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.run_test_case(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.run_test_case(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3155,7 +3408,7 @@ async def test_run_test_case_async(
transport: str = "grpc_asyncio", request_type=test_case.RunTestCaseRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3218,7 +3471,7 @@ def test_run_test_case_field_headers():
@pytest.mark.asyncio
async def test_run_test_case_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3282,6 +3535,27 @@ def test_batch_run_test_cases(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_batch_run_test_cases_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_run_test_cases), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.batch_run_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.BatchRunTestCasesRequest()
+
+
def test_batch_run_test_cases_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3346,9 +3620,8 @@ def test_batch_run_test_cases_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.batch_run_test_cases(request)
@@ -3358,6 +3631,29 @@ def test_batch_run_test_cases_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_batch_run_test_cases_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_run_test_cases), "__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.batch_run_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.BatchRunTestCasesRequest()
+
+
@pytest.mark.asyncio
async def test_batch_run_test_cases_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3366,7 +3662,7 @@ async def test_batch_run_test_cases_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3381,28 +3677,31 @@ async def test_batch_run_test_cases_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.batch_run_test_cases
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.batch_run_test_cases(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.batch_run_test_cases(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3410,7 +3709,7 @@ async def test_batch_run_test_cases_async(
transport: str = "grpc_asyncio", request_type=test_case.BatchRunTestCasesRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3477,7 +3776,7 @@ def test_batch_run_test_cases_field_headers():
@pytest.mark.asyncio
async def test_batch_run_test_cases_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3546,6 +3845,27 @@ def test_calculate_coverage(request_type, transport: str = "grpc"):
assert response.agent == "agent_value"
+def test_calculate_coverage_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.calculate_coverage), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.calculate_coverage()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.CalculateCoverageRequest()
+
+
def test_calculate_coverage_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3615,6 +3935,31 @@ def test_calculate_coverage_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_calculate_coverage_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.calculate_coverage), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ test_case.CalculateCoverageResponse(
+ agent="agent_value",
+ )
+ )
+ response = await client.calculate_coverage()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.CalculateCoverageRequest()
+
+
@pytest.mark.asyncio
async def test_calculate_coverage_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3623,7 +3968,7 @@ async def test_calculate_coverage_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3638,23 +3983,27 @@ async def test_calculate_coverage_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.calculate_coverage
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.calculate_coverage(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.calculate_coverage(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3662,7 +4011,7 @@ async def test_calculate_coverage_async(
transport: str = "grpc_asyncio", request_type=test_case.CalculateCoverageRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3732,7 +4081,7 @@ def test_calculate_coverage_field_headers():
@pytest.mark.asyncio
async def test_calculate_coverage_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3798,6 +4147,27 @@ def test_import_test_cases(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_import_test_cases_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.import_test_cases), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.import_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ImportTestCasesRequest()
+
+
def test_import_test_cases_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3860,9 +4230,8 @@ def test_import_test_cases_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.import_test_cases(request)
@@ -3872,6 +4241,29 @@ def test_import_test_cases_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_import_test_cases_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.import_test_cases), "__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.import_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ImportTestCasesRequest()
+
+
@pytest.mark.asyncio
async def test_import_test_cases_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3880,7 +4272,7 @@ async def test_import_test_cases_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3895,28 +4287,31 @@ async def test_import_test_cases_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.import_test_cases
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.import_test_cases(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.import_test_cases(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3924,7 +4319,7 @@ async def test_import_test_cases_async(
transport: str = "grpc_asyncio", request_type=test_case.ImportTestCasesRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3991,7 +4386,7 @@ def test_import_test_cases_field_headers():
@pytest.mark.asyncio
async def test_import_test_cases_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4057,6 +4452,27 @@ def test_export_test_cases(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_test_cases_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.export_test_cases), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ExportTestCasesRequest()
+
+
def test_export_test_cases_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4121,9 +4537,8 @@ def test_export_test_cases_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_test_cases(request)
@@ -4133,6 +4548,29 @@ def test_export_test_cases_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_test_cases_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.export_test_cases), "__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.export_test_cases()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ExportTestCasesRequest()
+
+
@pytest.mark.asyncio
async def test_export_test_cases_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4141,7 +4579,7 @@ async def test_export_test_cases_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4156,28 +4594,31 @@ async def test_export_test_cases_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_test_cases
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_test_cases(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_test_cases(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4185,7 +4626,7 @@ async def test_export_test_cases_async(
transport: str = "grpc_asyncio", request_type=test_case.ExportTestCasesRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4252,7 +4693,7 @@ def test_export_test_cases_field_headers():
@pytest.mark.asyncio
async def test_export_test_cases_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4321,6 +4762,27 @@ def test_list_test_case_results(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_test_case_results_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_test_case_results), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_test_case_results()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ListTestCaseResultsRequest()
+
+
def test_list_test_case_results_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4396,15 +4858,40 @@ def test_list_test_case_results_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_list_test_case_results_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
-):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport=transport,
+async def test_list_test_case_results_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_test_case_results), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ test_case.ListTestCaseResultsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_test_case_results()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.ListTestCaseResultsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_test_case_results_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
# Should wrap all calls on client creation
@@ -4418,23 +4905,27 @@ async def test_list_test_case_results_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_test_case_results
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_test_case_results(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_test_case_results(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4442,7 +4933,7 @@ async def test_list_test_case_results_async(
transport: str = "grpc_asyncio", request_type=test_case.ListTestCaseResultsRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4512,7 +5003,7 @@ def test_list_test_case_results_field_headers():
@pytest.mark.asyncio
async def test_list_test_case_results_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -4586,7 +5077,7 @@ def test_list_test_case_results_flattened_error():
@pytest.mark.asyncio
async def test_list_test_case_results_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4617,7 +5108,7 @@ async def test_list_test_case_results_flattened_async():
@pytest.mark.asyncio
async def test_list_test_case_results_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -4669,16 +5160,12 @@ def test_list_test_case_results_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_test_case_results(request={}, retry=retry, timeout=timeout)
+ pager = client.list_test_case_results(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -4731,7 +5218,7 @@ def test_list_test_case_results_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_test_case_results_async_pager():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4783,7 +5270,7 @@ async def test_list_test_case_results_async_pager():
@pytest.mark.asyncio
async def test_list_test_case_results_async_pages():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4873,6 +5360,27 @@ def test_get_test_case_result(request_type, transport: str = "grpc"):
assert response.test_result == test_case.TestResult.PASSED
+def test_get_test_case_result_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 = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_test_case_result), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_test_case_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.GetTestCaseResultRequest()
+
+
def test_get_test_case_result_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -4942,6 +5450,33 @@ def test_get_test_case_result_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_test_case_result_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_test_case_result), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ test_case.TestCaseResult(
+ name="name_value",
+ environment="environment_value",
+ test_result=test_case.TestResult.PASSED,
+ )
+ )
+ response = await client.get_test_case_result()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == test_case.GetTestCaseResultRequest()
+
+
@pytest.mark.asyncio
async def test_get_test_case_result_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -4950,7 +5485,7 @@ async def test_get_test_case_result_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -4965,23 +5500,27 @@ async def test_get_test_case_result_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_test_case_result
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_test_case_result(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_test_case_result(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -4989,7 +5528,7 @@ async def test_get_test_case_result_async(
transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseResultRequest
):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -5063,7 +5602,7 @@ def test_get_test_case_result_field_headers():
@pytest.mark.asyncio
async def test_get_test_case_result_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -5137,7 +5676,7 @@ def test_get_test_case_result_flattened_error():
@pytest.mark.asyncio
async def test_get_test_case_result_flattened_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -5168,7 +5707,7 @@ async def test_get_test_case_result_flattened_async():
@pytest.mark.asyncio
async def test_get_test_case_result_flattened_error_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -5180,6 +5719,46 @@ async def test_get_test_case_result_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ test_case.ListTestCasesRequest,
+ dict,
+ ],
+)
+def test_list_test_cases_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.ListTestCasesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.ListTestCasesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_test_cases(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListTestCasesPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_test_cases_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5316,6 +5895,83 @@ def test_list_test_cases_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_test_cases_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
+ )
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_list_test_cases"
+ ) as post, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_list_test_cases"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = test_case.ListTestCasesRequest.pb(test_case.ListTestCasesRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = test_case.ListTestCasesResponse.to_json(
+ test_case.ListTestCasesResponse()
+ )
+
+ request = test_case.ListTestCasesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = test_case.ListTestCasesResponse()
+
+ client.list_test_cases(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_test_cases_rest_bad_request(
+ transport: str = "rest", request_type=test_case.ListTestCasesRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_test_cases(request)
+
+
def test_list_test_cases_rest_flattened():
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5434,6 +6090,41 @@ def test_list_test_cases_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ test_case.BatchDeleteTestCasesRequest,
+ dict,
+ ],
+)
+def test_batch_delete_test_cases_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.batch_delete_test_cases(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_batch_delete_test_cases_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5568,10 +6259,81 @@ def test_batch_delete_test_cases_rest_unset_required_fields():
)
-def test_batch_delete_test_cases_rest_flattened():
- client = TestCasesClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_batch_delete_test_cases_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
+ )
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_batch_delete_test_cases"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = test_case.BatchDeleteTestCasesRequest.pb(
+ test_case.BatchDeleteTestCasesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = test_case.BatchDeleteTestCasesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.batch_delete_test_cases(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_batch_delete_test_cases_rest_bad_request(
+ transport: str = "rest", request_type=test_case.BatchDeleteTestCasesRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.batch_delete_test_cases(request)
+
+
+def test_batch_delete_test_cases_rest_flattened():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# Mock the http request call within the method and fake a response.
@@ -5623,6 +6385,60 @@ def test_batch_delete_test_cases_rest_flattened_error(transport: str = "rest"):
)
+def test_batch_delete_test_cases_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ test_case.GetTestCaseRequest,
+ dict,
+ ],
+)
+def test_get_test_case_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_test_case(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, test_case.TestCase)
+ assert response.name == "name_value"
+ assert response.tags == ["tags_value"]
+ assert response.display_name == "display_name_value"
+ assert response.notes == "notes_value"
+
+
def test_get_test_case_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -5740,6 +6556,83 @@ def test_get_test_case_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_test_case_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
+ )
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_get_test_case"
+ ) as post, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_get_test_case"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = test_case.GetTestCaseRequest.pb(test_case.GetTestCaseRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = test_case.TestCase.to_json(test_case.TestCase())
+
+ request = test_case.GetTestCaseRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = test_case.TestCase()
+
+ client.get_test_case(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_test_case_rest_bad_request(
+ transport: str = "rest", request_type=test_case.GetTestCaseRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_test_case(request)
+
+
def test_get_test_case_rest_flattened():
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5799,2574 +6692,24 @@ def test_get_test_case_rest_flattened_error(transport: str = "rest"):
)
-def test_create_test_case_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.create_test_case in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.create_test_case
- ] = mock_rpc
-
- request = {}
- client.create_test_case(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.create_test_case(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_create_test_case_rest_required_fields(
- request_type=gcdc_test_case.CreateTestCaseRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+def test_get_test_case_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_test_case._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_test_case._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_test_case.CreateTestCaseRequest,
+ dict,
+ ],
+)
+def test_create_test_case_rest(request_type):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.create_test_case(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_test_case_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_test_case._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "parent",
- "testCase",
- )
- )
- )
-
-
-def test_create_test_case_rest_flattened():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- test_case=gcdc_test_case.TestCase(name="name_value"),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.create_test_case(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_test_case_rest_flattened_error(transport: str = "rest"):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_test_case(
- gcdc_test_case.CreateTestCaseRequest(),
- parent="parent_value",
- test_case=gcdc_test_case.TestCase(name="name_value"),
- )
-
-
-def test_update_test_case_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_test_case in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.update_test_case
- ] = mock_rpc
-
- request = {}
- client.update_test_case(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.update_test_case(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_update_test_case_rest_required_fields(
- request_type=gcdc_test_case.UpdateTestCaseRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_test_case._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_test_case._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "patch",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.update_test_case(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_test_case_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_test_case._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("updateMask",))
- & set(
- (
- "testCase",
- "updateMask",
- )
- )
- )
-
-
-def test_update_test_case_rest_flattened():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "test_case": {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- test_case=gcdc_test_case.TestCase(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_test_case(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{test_case.name=projects/*/locations/*/agents/*/testCases/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_test_case_rest_flattened_error(transport: str = "rest"):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_test_case(
- gcdc_test_case.UpdateTestCaseRequest(),
- test_case=gcdc_test_case.TestCase(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_run_test_case_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.run_test_case in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.run_test_case] = mock_rpc
-
- request = {}
- client.run_test_case(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.run_test_case(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_run_test_case_rest_required_fields(request_type=test_case.RunTestCaseRequest):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).run_test_case._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).run_test_case._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.run_test_case(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_run_test_case_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.run_test_case._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-def test_batch_run_test_cases_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.batch_run_test_cases in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.batch_run_test_cases
- ] = mock_rpc
-
- request = {}
- client.batch_run_test_cases(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.batch_run_test_cases(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_batch_run_test_cases_rest_required_fields(
- request_type=test_case.BatchRunTestCasesRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request_init["test_cases"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).batch_run_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
- jsonified_request["testCases"] = "test_cases_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).batch_run_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
- assert "testCases" in jsonified_request
- assert jsonified_request["testCases"] == "test_cases_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.batch_run_test_cases(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_batch_run_test_cases_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.batch_run_test_cases._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(())
- & set(
- (
- "parent",
- "testCases",
- )
- )
- )
-
-
-def test_calculate_coverage_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.calculate_coverage in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.calculate_coverage
- ] = mock_rpc
-
- request = {}
- client.calculate_coverage(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.calculate_coverage(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_calculate_coverage_rest_required_fields(
- request_type=test_case.CalculateCoverageRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["agent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).calculate_coverage._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["agent"] = "agent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).calculate_coverage._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("type_",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "agent" in jsonified_request
- assert jsonified_request["agent"] == "agent_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = test_case.CalculateCoverageResponse()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.CalculateCoverageResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.calculate_coverage(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_calculate_coverage_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.calculate_coverage._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("type",))
- & set(
- (
- "agent",
- "type",
- )
- )
- )
-
-
-def test_import_test_cases_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.import_test_cases in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.import_test_cases
- ] = mock_rpc
-
- request = {}
- client.import_test_cases(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.import_test_cases(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_import_test_cases_rest_required_fields(
- request_type=test_case.ImportTestCasesRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).import_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).import_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.import_test_cases(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_import_test_cases_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.import_test_cases._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("parent",)))
-
-
-def test_export_test_cases_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.export_test_cases in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.export_test_cases
- ] = mock_rpc
-
- request = {}
- client.export_test_cases(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- # Operation methods build a cached wrapper on first rpc call
- # subsequent calls should use the cached wrapper
- wrapper_fn.reset_mock()
-
- client.export_test_cases(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_export_test_cases_rest_required_fields(
- request_type=test_case.ExportTestCasesRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).export_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).export_test_cases._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "post",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.export_test_cases(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_export_test_cases_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.export_test_cases._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("parent",)))
-
-
-def test_list_test_case_results_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.list_test_case_results
- in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.list_test_case_results
- ] = mock_rpc
-
- request = {}
- client.list_test_case_results(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.list_test_case_results(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_list_test_case_results_rest_required_fields(
- request_type=test_case.ListTestCaseResultsRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_test_case_results._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["parent"] = "parent_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_test_case_results._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "filter",
- "page_size",
- "page_token",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = test_case.ListTestCaseResultsResponse()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.list_test_case_results(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_list_test_case_results_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.list_test_case_results._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "filter",
- "pageSize",
- "pageToken",
- )
- )
- & set(("parent",))
- )
-
-
-def test_list_test_case_results_rest_flattened():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.ListTestCaseResultsResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.list_test_case_results(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/testCases/*}/results"
- % client.transport._host,
- args[1],
- )
-
-
-def test_list_test_case_results_rest_flattened_error(transport: str = "rest"):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_test_case_results(
- test_case.ListTestCaseResultsRequest(),
- parent="parent_value",
- )
-
-
-def test_list_test_case_results_rest_pager(transport: str = "rest"):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- test_case.ListTestCaseResultsResponse(
- test_case_results=[
- test_case.TestCaseResult(),
- test_case.TestCaseResult(),
- test_case.TestCaseResult(),
- ],
- next_page_token="abc",
- ),
- test_case.ListTestCaseResultsResponse(
- test_case_results=[],
- next_page_token="def",
- ),
- test_case.ListTestCaseResultsResponse(
- test_case_results=[
- test_case.TestCaseResult(),
- ],
- next_page_token="ghi",
- ),
- test_case.ListTestCaseResultsResponse(
- test_case_results=[
- test_case.TestCaseResult(),
- test_case.TestCaseResult(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- test_case.ListTestCaseResultsResponse.to_json(x) for x in response
- )
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
-
- pager = client.list_test_case_results(request=sample_request)
-
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, test_case.TestCaseResult) for i in results)
-
- pages = list(client.list_test_case_results(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-def test_get_test_case_result_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.get_test_case_result in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.get_test_case_result
- ] = mock_rpc
-
- request = {}
- client.get_test_case_result(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.get_test_case_result(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_get_test_case_result_rest_required_fields(
- request_type=test_case.GetTestCaseResultRequest,
-):
- transport_class = transports.TestCasesRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_test_case_result._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_test_case_result._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = test_case.TestCaseResult()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.TestCaseResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.get_test_case_result(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_test_case_result_rest_unset_required_fields():
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_test_case_result._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-def test_get_test_case_result_rest_flattened():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.TestCaseResult()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = test_case.TestCaseResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.get_test_case_result(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/testCases/*/results/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_test_case_result_rest_flattened_error(transport: str = "rest"):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_test_case_result(
- test_case.GetTestCaseResultRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TestCasesClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = TestCasesClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = TestCasesClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TestCasesClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = TestCasesClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.TestCasesGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.TestCasesGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.TestCasesGrpcTransport,
- transports.TestCasesGrpcAsyncIOTransport,
- transports.TestCasesRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = TestCasesClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_test_cases_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call:
- call.return_value = test_case.ListTestCasesResponse()
- client.list_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_batch_delete_test_cases_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_delete_test_cases), "__call__"
- ) as call:
- call.return_value = None
- client.batch_delete_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchDeleteTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_test_case_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_test_case), "__call__") as call:
- call.return_value = test_case.TestCase()
- client.get_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_test_case_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_test_case), "__call__") as call:
- call.return_value = gcdc_test_case.TestCase()
- client.create_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.CreateTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_test_case_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_test_case), "__call__") as call:
- call.return_value = gcdc_test_case.TestCase()
- client.update_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.UpdateTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_run_test_case_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.run_test_case), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.run_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.RunTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_batch_run_test_cases_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_run_test_cases), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.batch_run_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchRunTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_calculate_coverage_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.calculate_coverage), "__call__"
- ) as call:
- call.return_value = test_case.CalculateCoverageResponse()
- client.calculate_coverage(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.CalculateCoverageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_test_cases_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_test_cases), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.import_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ImportTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_test_cases_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_test_cases), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ExportTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_test_case_results_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_test_case_results), "__call__"
- ) as call:
- call.return_value = test_case.ListTestCaseResultsResponse()
- client.list_test_case_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCaseResultsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_test_case_result_empty_call_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_test_case_result), "__call__"
- ) as call:
- call.return_value = test_case.TestCaseResult()
- client.get_test_case_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseResultRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = TestCasesAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_test_cases_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- test_case.ListTestCasesResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_batch_delete_test_cases_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_delete_test_cases), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.batch_delete_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchDeleteTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_test_case_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_test_case), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
- )
- await client.get_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_test_case_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_test_case), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
- )
- await client.create_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.CreateTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_test_case_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_test_case), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
- )
- await client.update_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.UpdateTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_run_test_case_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.run_test_case), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.run_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.RunTestCaseRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_batch_run_test_cases_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_run_test_cases), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.batch_run_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchRunTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_calculate_coverage_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.calculate_coverage), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- test_case.CalculateCoverageResponse(
- agent="agent_value",
- )
- )
- await client.calculate_coverage(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.CalculateCoverageRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_import_test_cases_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_test_cases), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.import_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ImportTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_test_cases_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_test_cases), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.export_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ExportTestCasesRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_test_case_results_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_test_case_results), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- test_case.ListTestCaseResultsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_test_case_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCaseResultsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_test_case_result_empty_call_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_test_case_result), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- test_case.TestCaseResult(
- name="name_value",
- environment="environment_value",
- test_result=test_case.TestResult.PASSED,
- )
- )
- await client.get_test_case_result(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseResultRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = TestCasesClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_test_cases_rest_bad_request(request_type=test_case.ListTestCasesRequest):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_test_cases(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.ListTestCasesRequest,
- dict,
- ],
-)
-def test_list_test_cases_rest_call_success(request_type):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.ListTestCasesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.ListTestCasesResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_test_cases(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListTestCasesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_test_cases_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "post_list_test_cases"
- ) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_list_test_cases"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = test_case.ListTestCasesRequest.pb(test_case.ListTestCasesRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = test_case.ListTestCasesResponse.to_json(
- test_case.ListTestCasesResponse()
- )
- req.return_value.content = return_value
-
- request = test_case.ListTestCasesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = test_case.ListTestCasesResponse()
-
- client.list_test_cases(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_batch_delete_test_cases_rest_bad_request(
- request_type=test_case.BatchDeleteTestCasesRequest,
-):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.batch_delete_test_cases(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.BatchDeleteTestCasesRequest,
- dict,
- ],
-)
-def test_batch_delete_test_cases_rest_call_success(request_type):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.batch_delete_test_cases(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_batch_delete_test_cases_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_batch_delete_test_cases"
- ) as pre:
- pre.assert_not_called()
- pb_message = test_case.BatchDeleteTestCasesRequest.pb(
- test_case.BatchDeleteTestCasesRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = test_case.BatchDeleteTestCasesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.batch_delete_test_cases(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_test_case_rest_bad_request(request_type=test_case.GetTestCaseRequest):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_test_case(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.GetTestCaseRequest,
- dict,
- ],
-)
-def test_get_test_case_rest_call_success(request_type):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_test_case(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, test_case.TestCase)
- assert response.name == "name_value"
- assert response.tags == ["tags_value"]
- assert response.display_name == "display_name_value"
- assert response.notes == "notes_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_test_case_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "post_get_test_case"
- ) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_get_test_case"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = test_case.GetTestCaseRequest.pb(test_case.GetTestCaseRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = test_case.TestCase.to_json(test_case.TestCase())
- req.return_value.content = return_value
-
- request = test_case.GetTestCaseRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = test_case.TestCase()
-
- client.get_test_case(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_test_case_rest_bad_request(
- request_type=gcdc_test_case.CreateTestCaseRequest,
-):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_test_case(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_test_case.CreateTestCaseRequest,
- dict,
- ],
-)
-def test_create_test_case_rest_call_success(request_type):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
# send a request that will satisfy transcoding
request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
@@ -8552,7 +6895,6 @@ def test_create_test_case_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -8573,7 +6915,6 @@ def test_create_test_case_rest_call_success(request_type):
"trigger_fulfillment": {},
"target_page": "target_page_value",
"target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
}
],
},
@@ -8703,32 +7044,162 @@ def get_message_fields(field):
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_test_case(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_test_case.TestCase)
+ assert response.name == "name_value"
+ assert response.tags == ["tags_value"]
+ assert response.display_name == "display_name_value"
+ assert response.notes == "notes_value"
+
+
+def test_create_test_case_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_test_case in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.create_test_case
+ ] = mock_rpc
+
+ request = {}
+ client.create_test_case(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_test_case(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_create_test_case_rest_required_fields(
+ request_type=gcdc_test_case.CreateTestCaseRequest,
+):
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).create_test_case._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).create_test_case._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ response_value = Response()
+ response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_test_case(request)
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_test_case.TestCase)
- assert response.name == "name_value"
- assert response.tags == ["tags_value"]
- assert response.display_name == "display_name_value"
- assert response.notes == "notes_value"
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.create_test_case(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_create_test_case_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.create_test_case._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(())
+ & set(
+ (
+ "parent",
+ "testCase",
+ )
+ )
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -8738,7 +7209,6 @@ def test_create_test_case_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -8760,10 +7230,12 @@ def test_create_test_case_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_test_case.TestCase.to_json(gcdc_test_case.TestCase())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_test_case.TestCase.to_json(
+ gcdc_test_case.TestCase()
+ )
request = gcdc_test_case.CreateTestCaseRequest()
metadata = [
@@ -8785,18 +7257,16 @@ def test_create_test_case_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_update_test_case_rest_bad_request(
- request_type=gcdc_test_case.UpdateTestCaseRequest,
+def test_create_test_case_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_test_case.CreateTestCaseRequest
):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {
- "test_case": {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
- }
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -8804,13 +7274,76 @@ def test_update_test_case_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.update_test_case(request)
+ client.create_test_case(request)
+
+
+def test_create_test_case_rest_flattened():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ test_case=gcdc_test_case.TestCase(name="name_value"),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.create_test_case(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*}/testCases"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_create_test_case_rest_flattened_error(transport: str = "rest"):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_test_case(
+ gcdc_test_case.CreateTestCaseRequest(),
+ parent="parent_value",
+ test_case=gcdc_test_case.TestCase(name="name_value"),
+ )
+
+
+def test_create_test_case_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -8820,9 +7353,10 @@ def test_update_test_case_rest_bad_request(
dict,
],
)
-def test_update_test_case_rest_call_success(request_type):
+def test_update_test_case_rest(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -9013,7 +7547,6 @@ def test_update_test_case_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -9034,7 +7567,6 @@ def test_update_test_case_rest_call_success(request_type):
"trigger_fulfillment": {},
"target_page": "target_page_value",
"target_flow": "target_flow_value",
- "target_playbook": "target_playbook_value",
}
],
},
@@ -9164,32 +7696,159 @@ def get_message_fields(field):
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_test_case.TestCase(
- name="name_value",
- tags=["tags_value"],
- display_name="display_name_value",
- notes="notes_value",
- )
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase(
+ name="name_value",
+ tags=["tags_value"],
+ display_name="display_name_value",
+ notes="notes_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_test_case(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_test_case.TestCase)
+ assert response.name == "name_value"
+ assert response.tags == ["tags_value"]
+ assert response.display_name == "display_name_value"
+ assert response.notes == "notes_value"
+
+
+def test_update_test_case_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_test_case in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_test_case
+ ] = mock_rpc
+
+ request = {}
+ client.update_test_case(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_test_case(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_test_case_rest_required_fields(
+ request_type=gcdc_test_case.UpdateTestCaseRequest,
+):
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_test_case._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_test_case._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("update_mask",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "patch",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ response_value = Response()
+ response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_test_case.TestCase.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_test_case(request)
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_test_case.TestCase)
- assert response.name == "name_value"
- assert response.tags == ["tags_value"]
- assert response.display_name == "display_name_value"
- assert response.notes == "notes_value"
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.update_test_case(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_update_test_case_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.update_test_case._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("updateMask",))
+ & set(
+ (
+ "testCase",
+ "updateMask",
+ )
+ )
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -9199,7 +7858,6 @@ def test_update_test_case_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -9221,10 +7879,12 @@ def test_update_test_case_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_test_case.TestCase.to_json(gcdc_test_case.TestCase())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_test_case.TestCase.to_json(
+ gcdc_test_case.TestCase()
+ )
request = gcdc_test_case.UpdateTestCaseRequest()
metadata = [
@@ -9246,13 +7906,19 @@ def test_update_test_case_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_run_test_case_rest_bad_request(request_type=test_case.RunTestCaseRequest):
+def test_update_test_case_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_test_case.UpdateTestCaseRequest
+):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ "test_case": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
}
request = request_type(**request_init)
@@ -9261,13 +7927,80 @@ def test_run_test_case_rest_bad_request(request_type=test_case.RunTestCaseReques
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.run_test_case(request)
+ client.update_test_case(request)
+
+
+def test_update_test_case_rest_flattened():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_test_case.TestCase()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "test_case": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ test_case=gcdc_test_case.TestCase(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_test_case.TestCase.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ client.update_test_case(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{test_case.name=projects/*/locations/*/agents/*/testCases/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_test_case_rest_flattened_error(transport: str = "rest"):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_test_case(
+ gcdc_test_case.UpdateTestCaseRequest(),
+ test_case=gcdc_test_case.TestCase(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_update_test_case_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -9277,32 +8010,153 @@ def test_run_test_case_rest_bad_request(request_type=test_case.RunTestCaseReques
dict,
],
)
-def test_run_test_case_rest_call_success(request_type):
+def test_run_test_case_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.run_test_case(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_run_test_case_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.run_test_case in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.run_test_case] = mock_rpc
+
+ request = {}
+ client.run_test_case(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.run_test_case(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_run_test_case_rest_required_fields(request_type=test_case.RunTestCaseRequest):
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).run_test_case._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).run_test_case._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
+
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
request = request_type(**request_init)
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
# Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.run_test_case(request)
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.run_test_case(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_run_test_case_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.run_test_case._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -9312,7 +8166,6 @@ def test_run_test_case_rest_interceptors(null_interceptor):
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -9334,10 +8187,12 @@ def test_run_test_case_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
request = test_case.RunTestCaseRequest()
metadata = [
@@ -9359,14 +8214,18 @@ def test_run_test_case_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_batch_run_test_cases_rest_bad_request(
- request_type=test_case.BatchRunTestCasesRequest,
+def test_run_test_case_rest_bad_request(
+ transport: str = "rest", request_type=test_case.RunTestCaseRequest
):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -9374,13 +8233,17 @@ def test_batch_run_test_cases_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.batch_run_test_cases(request)
+ client.run_test_case(request)
+
+
+def test_run_test_case_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -9390,9 +8253,10 @@ def test_batch_run_test_cases_rest_bad_request(
dict,
],
)
-def test_batch_run_test_cases_rest_call_success(request_type):
+def test_batch_run_test_cases_rest(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -9405,157 +8269,177 @@ def test_batch_run_test_cases_rest_call_success(request_type):
return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.batch_run_test_cases(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert response.operation.name == "operations/spam"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_batch_run_test_cases_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.TestCasesRestInterceptor, "post_batch_run_test_cases"
- ) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_batch_run_test_cases"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = test_case.BatchRunTestCasesRequest.pb(
- test_case.BatchRunTestCasesRequest()
+def test_batch_run_test_cases_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = test_case.BatchRunTestCasesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ # Ensure method has been cached
+ assert (
+ client._transport.batch_run_test_cases in client._transport._wrapped_methods
+ )
- client.batch_run_test_cases(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[
+ client._transport.batch_run_test_cases
+ ] = mock_rpc
- pre.assert_called_once()
- post.assert_called_once()
+ request = {}
+ client.batch_run_test_cases(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_calculate_coverage_rest_bad_request(
- request_type=test_case.CalculateCoverageRequest,
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.batch_run_test_cases(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_batch_run_test_cases_rest_required_fields(
+ request_type=test_case.BatchRunTestCasesRequest,
):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"agent": "projects/sample1/locations/sample2/agents/sample3"}
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request_init["test_cases"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.calculate_coverage(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).batch_run_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+ jsonified_request["testCases"] = "test_cases_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).batch_run_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+ assert "testCases" in jsonified_request
+ assert jsonified_request["testCases"] == "test_cases_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.CalculateCoverageRequest,
- dict,
- ],
-)
-def test_calculate_coverage_rest_call_success(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
-
- # send a request that will satisfy transcoding
- request_init = {"agent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.CalculateCoverageResponse(
- agent="agent_value",
- )
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.batch_run_test_cases(request)
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Convert return value to protobuf type
- return_value = test_case.CalculateCoverageResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.calculate_coverage(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, test_case.CalculateCoverageResponse)
- assert response.agent == "agent_value"
+def test_batch_run_test_cases_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.batch_run_test_cases._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(())
+ & set(
+ (
+ "parent",
+ "testCases",
+ )
+ )
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_calculate_coverage_rest_interceptors(null_interceptor):
+def test_batch_run_test_cases_rest_interceptors(null_interceptor):
transport = transports.TestCasesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "post_calculate_coverage"
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_batch_run_test_cases"
) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_calculate_coverage"
+ transports.TestCasesRestInterceptor, "pre_batch_run_test_cases"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = test_case.CalculateCoverageRequest.pb(
- test_case.CalculateCoverageRequest()
+ pb_message = test_case.BatchRunTestCasesRequest.pb(
+ test_case.BatchRunTestCasesRequest()
)
transcode.return_value = {
"method": "post",
@@ -9564,22 +8448,22 @@ def test_calculate_coverage_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = test_case.CalculateCoverageResponse.to_json(
- test_case.CalculateCoverageResponse()
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- req.return_value.content = return_value
- request = test_case.CalculateCoverageRequest()
+ request = test_case.BatchRunTestCasesRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = test_case.CalculateCoverageResponse()
+ post.return_value = operations_pb2.Operation()
- client.calculate_coverage(
+ client.batch_run_test_cases(
request,
metadata=[
("key", "val"),
@@ -9591,12 +8475,14 @@ def test_calculate_coverage_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_import_test_cases_rest_bad_request(
- request_type=test_case.ImportTestCasesRequest,
+def test_batch_run_test_cases_rest_bad_request(
+ transport: str = "rest", request_type=test_case.BatchRunTestCasesRequest
):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
@@ -9606,184 +8492,212 @@ def test_import_test_cases_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.import_test_cases(request)
+ client.batch_run_test_cases(request)
+
+
+def test_batch_run_test_cases_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- test_case.ImportTestCasesRequest,
+ test_case.CalculateCoverageRequest,
dict,
],
)
-def test_import_test_cases_rest_call_success(request_type):
+def test_calculate_coverage_rest(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init = {"agent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = test_case.CalculateCoverageResponse(
+ agent="agent_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.CalculateCoverageResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.import_test_cases(request)
+ response = client.calculate_coverage(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
+ assert isinstance(response, test_case.CalculateCoverageResponse)
+ assert response.agent == "agent_value"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_import_test_cases_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.TestCasesRestInterceptor, "post_import_test_cases"
- ) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_import_test_cases"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = test_case.ImportTestCasesRequest.pb(
- test_case.ImportTestCasesRequest()
+def test_calculate_coverage_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = test_case.ImportTestCasesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ # Ensure method has been cached
+ assert (
+ client._transport.calculate_coverage in client._transport._wrapped_methods
+ )
- client.import_test_cases(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[
+ client._transport.calculate_coverage
+ ] = mock_rpc
- pre.assert_called_once()
- post.assert_called_once()
+ request = {}
+ client.calculate_coverage(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_export_test_cases_rest_bad_request(
- request_type=test_case.ExportTestCasesRequest,
+ client.calculate_coverage(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_calculate_coverage_rest_required_fields(
+ request_type=test_case.CalculateCoverageRequest,
):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["agent"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_test_cases(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).calculate_coverage._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["agent"] = "agent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).calculate_coverage._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("type_",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "agent" in jsonified_request
+ assert jsonified_request["agent"] == "agent_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.ExportTestCasesRequest,
- dict,
- ],
-)
-def test_export_test_cases_rest_call_success(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.CalculateCoverageResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = test_case.CalculateCoverageResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.calculate_coverage(request)
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_test_cases(request)
+def test_calculate_coverage_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ unset_fields = transport.calculate_coverage._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(("type",))
+ & set(
+ (
+ "agent",
+ "type",
+ )
+ )
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_test_cases_rest_interceptors(null_interceptor):
+def test_calculate_coverage_rest_interceptors(null_interceptor):
transport = transports.TestCasesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.TestCasesRestInterceptor, "post_export_test_cases"
+ transports.TestCasesRestInterceptor, "post_calculate_coverage"
) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_export_test_cases"
+ transports.TestCasesRestInterceptor, "pre_calculate_coverage"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = test_case.ExportTestCasesRequest.pb(
- test_case.ExportTestCasesRequest()
+ pb_message = test_case.CalculateCoverageRequest.pb(
+ test_case.CalculateCoverageRequest()
)
transcode.return_value = {
"method": "post",
@@ -9792,20 +8706,22 @@ def test_export_test_cases_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = test_case.CalculateCoverageResponse.to_json(
+ test_case.CalculateCoverageResponse()
+ )
- request = test_case.ExportTestCasesRequest()
+ request = test_case.CalculateCoverageRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ post.return_value = test_case.CalculateCoverageResponse()
- client.export_test_cases(
+ client.calculate_coverage(
request,
metadata=[
("key", "val"),
@@ -9817,16 +8733,16 @@ def test_export_test_cases_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_list_test_case_results_rest_bad_request(
- request_type=test_case.ListTestCaseResultsRequest,
+def test_calculate_coverage_rest_bad_request(
+ transport: str = "rest", request_type=test_case.CalculateCoverageRequest
):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
+ request_init = {"agent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -9834,204 +8750,199 @@ def test_list_test_case_results_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.list_test_case_results(request)
+ client.calculate_coverage(request)
+
+
+def test_calculate_coverage_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- test_case.ListTestCaseResultsRequest,
+ test_case.ImportTestCasesRequest,
dict,
],
)
-def test_list_test_case_results_rest_call_success(request_type):
+def test_import_test_cases_rest(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
- }
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = test_case.ListTestCaseResultsResponse(
- next_page_token="next_page_token_value",
- )
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_test_case_results(request)
+ response = client.import_test_cases(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListTestCaseResultsPager)
- assert response.next_page_token == "next_page_token_value"
+ assert response.operation.name == "operations/spam"
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_test_case_results_rest_interceptors(null_interceptor):
- transport = transports.TestCasesRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
- )
- client = TestCasesClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "post_list_test_case_results"
- ) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_list_test_case_results"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = test_case.ListTestCaseResultsRequest.pb(
- test_case.ListTestCaseResultsRequest()
+def test_import_test_cases_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = test_case.ListTestCaseResultsResponse.to_json(
- test_case.ListTestCaseResultsResponse()
- )
- req.return_value.content = return_value
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- request = test_case.ListTestCaseResultsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = test_case.ListTestCaseResultsResponse()
+ # Ensure method has been cached
+ assert client._transport.import_test_cases in client._transport._wrapped_methods
- client.list_test_case_results(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[
+ client._transport.import_test_cases
+ ] = mock_rpc
- pre.assert_called_once()
- post.assert_called_once()
+ request = {}
+ client.import_test_cases(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_get_test_case_result_rest_bad_request(
- request_type=test_case.GetTestCaseResultRequest,
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.import_test_cases(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_import_test_cases_rest_required_fields(
+ request_type=test_case.ImportTestCasesRequest,
):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
- }
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_test_case_result(request)
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).import_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).import_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- test_case.GetTestCaseResultRequest,
- dict,
- ],
-)
-def test_get_test_case_result_rest_call_success(request_type):
client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
- }
- request = request_type(**request_init)
+ response = client.import_test_cases(request)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = test_case.TestCaseResult(
- name="name_value",
- environment="environment_value",
- test_result=test_case.TestResult.PASSED,
- )
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = test_case.TestCaseResult.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_test_case_result(request)
+def test_import_test_cases_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, test_case.TestCaseResult)
- assert response.name == "name_value"
- assert response.environment == "environment_value"
- assert response.test_result == test_case.TestResult.PASSED
+ unset_fields = transport.import_test_cases._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("parent",)))
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_test_case_result_rest_interceptors(null_interceptor):
+def test_import_test_cases_rest_interceptors(null_interceptor):
transport = transports.TestCasesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
client = TestCasesClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
path_template, "transcode"
) as transcode, mock.patch.object(
- transports.TestCasesRestInterceptor, "post_get_test_case_result"
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_import_test_cases"
) as post, mock.patch.object(
- transports.TestCasesRestInterceptor, "pre_get_test_case_result"
+ transports.TestCasesRestInterceptor, "pre_import_test_cases"
) as pre:
pre.assert_not_called()
post.assert_not_called()
- pb_message = test_case.GetTestCaseResultRequest.pb(
- test_case.GetTestCaseResultRequest()
+ pb_message = test_case.ImportTestCasesRequest.pb(
+ test_case.ImportTestCasesRequest()
)
transcode.return_value = {
"method": "post",
@@ -10040,20 +8951,22 @@ def test_get_test_case_result_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = test_case.TestCaseResult.to_json(test_case.TestCaseResult())
- req.return_value.content = return_value
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- request = test_case.GetTestCaseResultRequest()
+ request = test_case.ImportTestCasesRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = test_case.TestCaseResult()
+ post.return_value = operations_pb2.Operation()
- client.get_test_case_result(
+ client.import_test_cases(
request,
metadata=[
("key", "val"),
@@ -10065,73 +8978,262 @@ def test_get_test_case_result_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_import_test_cases_rest_bad_request(
+ transport: str = "rest", request_type=test_case.ImportTestCasesRequest
+):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_location(request)
+ client.import_test_cases(request)
+
+
+def test_import_test_cases_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.GetLocationRequest,
+ test_case.ExportTestCasesRequest,
dict,
],
)
-def test_get_location_rest(request_type):
+def test_export_test_cases_rest(request_type):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = operations_pb2.Operation(name="operations/spam")
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
+ response = client.export_test_cases(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
+def test_export_test_cases_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.export_test_cases in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.export_test_cases
+ ] = mock_rpc
+
+ request = {}
+ client.export_test_cases(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.export_test_cases(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_export_test_cases_rest_required_fields(
+ request_type=test_case.ExportTestCasesRequest,
+):
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).export_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).export_test_cases._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "post",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.export_test_cases(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_export_test_cases_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.export_test_cases._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("parent",)))
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_test_cases_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
+ )
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_export_test_cases"
+ ) as post, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_export_test_cases"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = test_case.ExportTestCasesRequest.pb(
+ test_case.ExportTestCasesRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
+
+ request = test_case.ExportTestCasesRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- response = client.get_location(request)
+ client.export_test_cases(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
+def test_export_test_cases_rest_bad_request(
+ transport: str = "rest", request_type=test_case.ExportTestCasesRequest
):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -10139,502 +9241,825 @@ def test_list_locations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_locations(request)
+ client.export_test_cases(request)
+
+
+def test_export_test_cases_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.ListLocationsRequest,
+ test_case.ListTestCaseResultsRequest,
dict,
],
)
-def test_list_locations_rest(request_type):
+def test_list_test_case_results_rest(request_type):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ return_value = test_case.ListTestCaseResultsResponse(
+ next_page_token="next_page_token_value",
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.list_locations(request)
+ response = client.list_test_case_results(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ assert isinstance(response, pagers.ListTestCaseResultsPager)
+ assert response.next_page_token == "next_page_token_value"
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
+def test_list_test_case_results_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.list_test_case_results
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.list_test_case_results
+ ] = mock_rpc
+
+ request = {}
+ client.list_test_case_results(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_test_case_results(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_list_test_case_results_rest_required_fields(
+ request_type=test_case.ListTestCaseResultsRequest,
):
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_test_case_results._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["parent"] = "parent_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).list_test_case_results._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "filter",
+ "page_size",
+ "page_token",
+ )
+ )
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1/operations/sample2"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.ListTestCaseResultsResponse()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
- req.return_value = response_value
+ # Convert return value to protobuf type
+ return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_test_case_results(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_list_test_case_results_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.list_test_case_results._get_unset_required_fields({})
+ assert set(unset_fields) == (
+ set(
+ (
+ "filter",
+ "pageSize",
+ "pageToken",
+ )
+ )
+ & set(("parent",))
+ )
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_test_case_results_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
+ )
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_list_test_case_results"
+ ) as post, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_list_test_case_results"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = test_case.ListTestCaseResultsRequest.pb(
+ test_case.ListTestCaseResultsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = test_case.ListTestCaseResultsResponse.to_json(
+ test_case.ListTestCaseResultsResponse()
+ )
+
+ request = test_case.ListTestCaseResultsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = test_case.ListTestCaseResultsResponse()
- response = client.cancel_operation(request)
+ client.list_test_case_results(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert response is None
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
+def test_list_test_case_results_rest_bad_request(
+ transport: str = "rest", request_type=test_case.ListTestCaseResultsRequest
):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_operation(request)
+ client.list_test_case_results(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
+def test_list_test_case_results_rest_flattened():
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ return_value = test_case.ListTestCaseResultsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.ListTestCaseResultsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.get_operation(request)
+ client.list_test_case_results(**mock_args)
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/testCases/*}/results"
+ % client.transport._host,
+ args[1],
+ )
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
+def test_list_test_case_results_rest_flattened_error(transport: str = "rest"):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_test_case_results(
+ test_case.ListTestCaseResultsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_test_case_results_rest_pager(transport: str = "rest"):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # TODO(kbandes): remove this mock unless there's a good reason for it.
+ # with mock.patch.object(path_template, 'transcode') as transcode:
+ # Set the response as a series of pages
+ response = (
+ test_case.ListTestCaseResultsResponse(
+ test_case_results=[
+ test_case.TestCaseResult(),
+ test_case.TestCaseResult(),
+ test_case.TestCaseResult(),
+ ],
+ next_page_token="abc",
+ ),
+ test_case.ListTestCaseResultsResponse(
+ test_case_results=[],
+ next_page_token="def",
+ ),
+ test_case.ListTestCaseResultsResponse(
+ test_case_results=[
+ test_case.TestCaseResult(),
+ ],
+ next_page_token="ghi",
+ ),
+ test_case.ListTestCaseResultsResponse(
+ test_case_results=[
+ test_case.TestCaseResult(),
+ test_case.TestCaseResult(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ test_case.ListTestCaseResultsResponse.to_json(x) for x in response
+ )
+ return_values = tuple(Response() for i in response)
+ for return_val, response_val in zip(return_values, response):
+ return_val._content = response_val.encode("UTF-8")
+ return_val.status_code = 200
+ req.side_effect = return_values
+
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4"
+ }
+
+ pager = client.list_test_case_results(request=sample_request)
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, test_case.TestCaseResult) for i in results)
+
+ pages = list(client.list_test_case_results(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
@pytest.mark.parametrize(
"request_type",
[
- operations_pb2.ListOperationsRequest,
+ test_case.GetTestCaseResultRequest,
dict,
],
)
-def test_list_operations_rest(request_type):
+def test_get_test_case_result_rest(request_type):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ return_value = test_case.TestCaseResult(
+ name="name_value",
+ environment="environment_value",
+ test_result=test_case.TestResult.PASSED,
+ )
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.TestCaseResult.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.list_operations(request)
+ response = client.get_test_case_result(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ assert isinstance(response, test_case.TestCaseResult)
+ assert response.name == "name_value"
+ assert response.environment == "environment_value"
+ assert response.test_result == test_case.TestResult.PASSED
-def test_initialize_client_w_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
+def test_get_test_case_result_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_test_cases_empty_call_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Ensure method has been cached
+ assert (
+ client._transport.get_test_case_result in client._transport._wrapped_methods
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call:
- client.list_test_cases(request=None)
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.get_test_case_result
+ ] = mock_rpc
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCasesRequest()
+ request = {}
+ client.get_test_case_result(request)
- assert args[0] == request_msg
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+ client.get_test_case_result(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_batch_delete_test_cases_empty_call_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_get_test_case_result_rest_required_fields(
+ request_type=test_case.GetTestCaseResultRequest,
+):
+ transport_class = transports.TestCasesRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_delete_test_cases), "__call__"
- ) as call:
- client.batch_delete_test_cases(request=None)
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_test_case_result._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchDeleteTestCasesRequest()
+ jsonified_request["name"] = "name_value"
- assert args[0] == request_msg
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).get_test_case_result._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_test_case_empty_call_rest():
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
+ request = request_type(**request_init)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_test_case), "__call__") as call:
- client.get_test_case(request=None)
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.TestCaseResult()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseRequest()
+ response_value = Response()
+ response_value.status_code = 200
- assert args[0] == request_msg
+ # Convert return value to protobuf type
+ return_value = test_case.TestCaseResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_test_case_empty_call_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ response = client.get_test_case_result(request)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_test_case), "__call__") as call:
- client.create_test_case(request=None)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.CreateTestCaseRequest()
- assert args[0] == request_msg
+def test_get_test_case_result_rest_unset_required_fields():
+ transport = transports.TestCasesRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+ unset_fields = transport.get_test_case_result._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_test_case_empty_call_rest():
- client = TestCasesClient(
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_test_case_result_rest_interceptors(null_interceptor):
+ transport = transports.TestCasesRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.TestCasesRestInterceptor(),
)
+ client = TestCasesClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TestCasesRestInterceptor, "post_get_test_case_result"
+ ) as post, mock.patch.object(
+ transports.TestCasesRestInterceptor, "pre_get_test_case_result"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = test_case.GetTestCaseResultRequest.pb(
+ test_case.GetTestCaseResultRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_test_case), "__call__") as call:
- client.update_test_case(request=None)
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = test_case.TestCaseResult.to_json(
+ test_case.TestCaseResult()
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_test_case.UpdateTestCaseRequest()
+ request = test_case.GetTestCaseResultRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = test_case.TestCaseResult()
+
+ client.get_test_case_result(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- assert args[0] == request_msg
+ pre.assert_called_once()
+ post.assert_called_once()
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_run_test_case_empty_call_rest():
+def test_get_test_case_result_rest_bad_request(
+ transport: str = "rest", request_type=test_case.GetTestCaseResultRequest
+):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.run_test_case), "__call__") as call:
- client.run_test_case(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.RunTestCaseRequest()
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
+ }
+ request = request_type(**request_init)
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_test_case_result(request)
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_batch_run_test_cases_empty_call_rest():
+def test_get_test_case_result_rest_flattened():
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.batch_run_test_cases), "__call__"
- ) as call:
- client.batch_run_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.BatchRunTestCasesRequest()
-
- assert args[0] == request_msg
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = test_case.TestCaseResult()
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/testCases/sample4/results/sample5"
+ }
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_calculate_coverage_empty_call_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.calculate_coverage), "__call__"
- ) as call:
- client.calculate_coverage(request=None)
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = test_case.TestCaseResult.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.CalculateCoverageRequest()
+ client.get_test_case_result(**mock_args)
- assert args[0] == request_msg
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/testCases/*/results/*}"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_import_test_cases_empty_call_rest():
+def test_get_test_case_result_rest_flattened_error(transport: str = "rest"):
client = TestCasesClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.import_test_cases), "__call__"
- ) as call:
- client.import_test_cases(request=None)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_test_case_result(
+ test_case.GetTestCaseResultRequest(),
+ name="name_value",
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ImportTestCasesRequest()
- assert args[0] == request_msg
+def test_get_test_case_result_rest_error():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_test_cases_empty_call_rest():
- client = TestCasesClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.TestCasesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.export_test_cases), "__call__"
- ) as call:
- client.export_test_cases(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ExportTestCasesRequest()
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.TestCasesGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = TestCasesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- assert args[0] == request_msg
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.TestCasesGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = TestCasesClient(
+ client_options=options,
+ transport=transport,
+ )
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = TestCasesClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_test_case_results_empty_call_rest():
- client = TestCasesClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.TestCasesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = TestCasesClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_test_case_results), "__call__"
- ) as call:
- client.list_test_case_results(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.ListTestCaseResultsRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.TestCasesGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = TestCasesClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_test_case_result_empty_call_rest():
- client = TestCasesClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.TestCasesGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_test_case_result), "__call__"
- ) as call:
- client.get_test_case_result(request=None)
+ transport = transports.TestCasesGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = test_case.GetTestCaseResultRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TestCasesGrpcTransport,
+ transports.TestCasesGrpcAsyncIOTransport,
+ transports.TestCasesRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_test_cases_rest_lro_client():
- client = TestCasesClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = TestCasesClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -10896,6 +10321,23 @@ def test_test_cases_http_transport_client_cert_source_for_mtls():
mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_test_cases_rest_lro_client():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
@pytest.mark.parametrize(
"transport_name",
[
@@ -11325,316 +10767,587 @@ def test_parse_page_path():
assert expected == actual
-def test_playbook_path():
+def test_test_case_path():
+ project = "squid"
+ location = "clam"
+ agent = "whelk"
+ test_case = "octopus"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ test_case=test_case,
+ )
+ actual = TestCasesClient.test_case_path(project, location, agent, test_case)
+ assert expected == actual
+
+
+def test_parse_test_case_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "agent": "cuttlefish",
+ "test_case": "mussel",
+ }
+ path = TestCasesClient.test_case_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_test_case_path(path)
+ assert expected == actual
+
+
+def test_test_case_result_path():
+ project = "winkle"
+ location = "nautilus"
+ agent = "scallop"
+ test_case = "abalone"
+ result = "squid"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ test_case=test_case,
+ result=result,
+ )
+ actual = TestCasesClient.test_case_result_path(
+ project, location, agent, test_case, result
+ )
+ assert expected == actual
+
+
+def test_parse_test_case_result_path():
+ expected = {
+ "project": "clam",
+ "location": "whelk",
+ "agent": "octopus",
+ "test_case": "oyster",
+ "result": "nudibranch",
+ }
+ path = TestCasesClient.test_case_result_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_test_case_result_path(path)
+ assert expected == actual
+
+
+def test_tool_path():
+ project = "cuttlefish"
+ location = "mussel"
+ agent = "winkle"
+ tool = "nautilus"
+ expected = (
+ "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ tool=tool,
+ )
+ )
+ actual = TestCasesClient.tool_path(project, location, agent, tool)
+ assert expected == actual
+
+
+def test_parse_tool_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ "agent": "squid",
+ "tool": "clam",
+ }
+ path = TestCasesClient.tool_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_tool_path(path)
+ assert expected == actual
+
+
+def test_transition_route_group_path():
+ project = "whelk"
+ location = "octopus"
+ agent = "oyster"
+ flow = "nudibranch"
+ transition_route_group = "cuttlefish"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
+ project=project,
+ location=location,
+ agent=agent,
+ flow=flow,
+ transition_route_group=transition_route_group,
+ )
+ actual = TestCasesClient.transition_route_group_path(
+ project, location, agent, flow, transition_route_group
+ )
+ assert expected == actual
+
+
+def test_parse_transition_route_group_path():
+ expected = {
+ "project": "mussel",
+ "location": "winkle",
+ "agent": "nautilus",
+ "flow": "scallop",
+ "transition_route_group": "abalone",
+ }
+ path = TestCasesClient.transition_route_group_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_transition_route_group_path(path)
+ assert expected == actual
+
+
+def test_webhook_path():
project = "squid"
location = "clam"
agent = "whelk"
- playbook = "octopus"
- expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format(
+ webhook = "octopus"
+ expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
project=project,
location=location,
agent=agent,
- playbook=playbook,
+ webhook=webhook,
+ )
+ actual = TestCasesClient.webhook_path(project, location, agent, webhook)
+ assert expected == actual
+
+
+def test_parse_webhook_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "agent": "cuttlefish",
+ "webhook": "mussel",
+ }
+ path = TestCasesClient.webhook_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_webhook_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "winkle"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = TestCasesClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nautilus",
+ }
+ path = TestCasesClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = TestCasesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = TestCasesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TestCasesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
)
- actual = TestCasesClient.playbook_path(project, location, agent, playbook)
+ actual = TestCasesClient.common_organization_path(organization)
assert expected == actual
-def test_parse_playbook_path():
+def test_parse_common_organization_path():
expected = {
- "project": "oyster",
- "location": "nudibranch",
- "agent": "cuttlefish",
- "playbook": "mussel",
+ "organization": "clam",
}
- path = TestCasesClient.playbook_path(**expected)
+ path = TestCasesClient.common_organization_path(**expected)
# Check that the path construction is reversible.
- actual = TestCasesClient.parse_playbook_path(path)
+ actual = TestCasesClient.parse_common_organization_path(path)
assert expected == actual
-def test_test_case_path():
- project = "winkle"
- location = "nautilus"
- agent = "scallop"
- test_case = "abalone"
- expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
project=project,
- location=location,
- agent=agent,
- test_case=test_case,
)
- actual = TestCasesClient.test_case_path(project, location, agent, test_case)
+ actual = TestCasesClient.common_project_path(project)
assert expected == actual
-def test_parse_test_case_path():
+def test_parse_common_project_path():
expected = {
- "project": "squid",
- "location": "clam",
- "agent": "whelk",
- "test_case": "octopus",
+ "project": "octopus",
}
- path = TestCasesClient.test_case_path(**expected)
+ path = TestCasesClient.common_project_path(**expected)
# Check that the path construction is reversible.
- actual = TestCasesClient.parse_test_case_path(path)
+ actual = TestCasesClient.parse_common_project_path(path)
assert expected == actual
-def test_test_case_result_path():
+def test_common_location_path():
project = "oyster"
location = "nudibranch"
- agent = "cuttlefish"
- test_case = "mussel"
- result = "winkle"
- expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(
+ expected = "projects/{project}/locations/{location}".format(
project=project,
location=location,
- agent=agent,
- test_case=test_case,
- result=result,
- )
- actual = TestCasesClient.test_case_result_path(
- project, location, agent, test_case, result
)
+ actual = TestCasesClient.common_location_path(project, location)
assert expected == actual
-def test_parse_test_case_result_path():
+def test_parse_common_location_path():
expected = {
- "project": "nautilus",
- "location": "scallop",
- "agent": "abalone",
- "test_case": "squid",
- "result": "clam",
+ "project": "cuttlefish",
+ "location": "mussel",
}
- path = TestCasesClient.test_case_result_path(**expected)
+ path = TestCasesClient.common_location_path(**expected)
# Check that the path construction is reversible.
- actual = TestCasesClient.parse_test_case_result_path(path)
+ actual = TestCasesClient.parse_common_location_path(path)
assert expected == actual
-def test_tool_path():
- project = "whelk"
- location = "octopus"
- agent = "oyster"
- tool = "nudibranch"
- expected = (
- "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format(
- project=project,
- location=location,
- agent=agent,
- tool=tool,
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.TestCasesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
)
- )
- actual = TestCasesClient.tool_path(project, location, agent, tool)
- assert expected == actual
+ prep.assert_called_once_with(client_info)
+ with mock.patch.object(
+ transports.TestCasesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = TestCasesClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
-def test_parse_tool_path():
- expected = {
- "project": "cuttlefish",
- "location": "mussel",
- "agent": "winkle",
- "tool": "nautilus",
- }
- path = TestCasesClient.tool_path(**expected)
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_tool_path(path)
- assert expected == actual
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = TestCasesAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
-def test_transition_route_group_path():
- project = "scallop"
- location = "abalone"
- agent = "squid"
- flow = "clam"
- transition_route_group = "whelk"
- expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(
- project=project,
- location=location,
- agent=agent,
- flow=flow,
- transition_route_group=transition_route_group,
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = TestCasesClient.transition_route_group_path(
- project, location, agent, flow, transition_route_group
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
)
- assert expected == actual
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
-def test_parse_transition_route_group_path():
- expected = {
- "project": "octopus",
- "location": "oyster",
- "agent": "nudibranch",
- "flow": "cuttlefish",
- "transition_route_group": "mussel",
- }
- path = TestCasesClient.transition_route_group_path(**expected)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_transition_route_group_path(path)
- assert expected == actual
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
-def test_webhook_path():
- project = "winkle"
- location = "nautilus"
- agent = "scallop"
- webhook = "abalone"
- expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(
- project=project,
- location=location,
- agent=agent,
- webhook=webhook,
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = TestCasesClient.webhook_path(project, location, agent, webhook)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_webhook_path():
- expected = {
- "project": "squid",
- "location": "clam",
- "agent": "whelk",
- "webhook": "octopus",
- }
- path = TestCasesClient.webhook_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_webhook_path(path)
- assert expected == actual
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_billing_account_path():
- billing_account = "oyster"
- expected = "billingAccounts/{billing_account}".format(
- billing_account=billing_account,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = TestCasesClient.common_billing_account_path(billing_account)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "nudibranch",
- }
- path = TestCasesClient.common_billing_account_path(**expected)
+ response = client.cancel_operation(request)
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = TestCasesClient.common_folder_path(folder)
- assert expected == actual
-
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = TestCasesClient.common_folder_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_common_folder_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = TestCasesClient.common_organization_path(organization)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = TestCasesClient.common_organization_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_common_organization_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
- )
- actual = TestCasesClient.common_project_path(project)
- assert expected == actual
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = TestCasesClient.common_project_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_common_project_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = TestCasesClient.common_location_path(project, location)
- assert expected == actual
-
-
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = TestCasesClient.common_location_path(**expected)
-
- # Check that the path construction is reversible.
- actual = TestCasesClient.parse_common_location_path(path)
- assert expected == actual
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.TestCasesTransport, "_prep_wrapped_messages"
- ) as prep:
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
- with mock.patch.object(
- transports.TestCasesTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = TestCasesClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -11664,7 +11377,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -11717,7 +11430,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -11762,7 +11475,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -11803,7 +11516,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -11858,7 +11571,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -11905,7 +11618,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -11948,7 +11661,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -12003,7 +11716,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -12050,7 +11763,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -12093,7 +11806,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -12148,7 +11861,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -12195,7 +11908,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -12238,7 +11951,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -12290,7 +12003,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = TestCasesAsyncClient(credentials=async_anonymous_credentials())
+ client = TestCasesAsyncClient(credentials=ga_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.
@@ -12336,7 +12049,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -12352,41 +12065,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = TestCasesAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = TestCasesClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = TestCasesClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_tools.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_tools.py
index 5d46ccd88c8f..b65585ada457 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_tools.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_tools.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -63,7 +45,15 @@
from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.tools import (
ToolsAsyncClient,
@@ -76,24 +66,10 @@
from google.cloud.dialogflowcx_v3beta1.types import tool as gcdc_tool
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1128,6 +1104,25 @@ def test_create_tool(request_type, transport: str = "grpc"):
assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
+def test_create_tool_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_tool), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_tool.CreateToolRequest()
+
+
def test_create_tool_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1191,6 +1186,32 @@ def test_create_tool_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_tool_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_tool), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_tool.Tool(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
+ )
+ )
+ response = await client.create_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_tool.CreateToolRequest()
+
+
@pytest.mark.asyncio
async def test_create_tool_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1199,7 +1220,7 @@ async def test_create_tool_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1214,23 +1235,27 @@ async def test_create_tool_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_tool
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_tool(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1238,7 +1263,7 @@ async def test_create_tool_async(
transport: str = "grpc_asyncio", request_type=gcdc_tool.CreateToolRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1310,7 +1335,7 @@ def test_create_tool_field_headers():
@pytest.mark.asyncio
async def test_create_tool_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1383,7 +1408,7 @@ def test_create_tool_flattened_error():
@pytest.mark.asyncio
async def test_create_tool_flattened_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1414,7 +1439,7 @@ async def test_create_tool_flattened_async():
@pytest.mark.asyncio
async def test_create_tool_flattened_error_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1463,6 +1488,25 @@ def test_list_tools(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_tools_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_tools), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_tools()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.ListToolsRequest()
+
+
def test_list_tools_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1528,13 +1572,36 @@ def test_list_tools_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_tools_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_tools), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ tool.ListToolsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_tools()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.ListToolsRequest()
+
+
@pytest.mark.asyncio
async def test_list_tools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1549,23 +1616,27 @@ async def test_list_tools_async_use_cached_wrapped_rpc(transport: str = "grpc_as
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_tools
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_tools(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_tools(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1573,7 +1644,7 @@ async def test_list_tools_async(
transport: str = "grpc_asyncio", request_type=tool.ListToolsRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1639,7 +1710,7 @@ def test_list_tools_field_headers():
@pytest.mark.asyncio
async def test_list_tools_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1709,7 +1780,7 @@ def test_list_tools_flattened_error():
@pytest.mark.asyncio
async def test_list_tools_flattened_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1738,7 +1809,7 @@ async def test_list_tools_flattened_async():
@pytest.mark.asyncio
async def test_list_tools_flattened_error_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1788,16 +1859,12 @@ def test_list_tools_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_tools(request={}, retry=retry, timeout=timeout)
+ pager = client.list_tools(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1848,7 +1915,7 @@ def test_list_tools_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_tools_async_pager():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1898,7 +1965,7 @@ async def test_list_tools_async_pager():
@pytest.mark.asyncio
async def test_list_tools_async_pages():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1977,6 +2044,25 @@ def test_export_tools(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_export_tools_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_tools), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.export_tools()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.ExportToolsRequest()
+
+
def test_export_tools_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2035,9 +2121,8 @@ def test_export_tools_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.export_tools(request)
@@ -2047,6 +2132,27 @@ def test_export_tools_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_export_tools_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.export_tools), "__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.export_tools()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.ExportToolsRequest()
+
+
@pytest.mark.asyncio
async def test_export_tools_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2055,7 +2161,7 @@ async def test_export_tools_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2070,28 +2176,31 @@ async def test_export_tools_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.export_tools
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.export_tools(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.export_tools(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2099,7 +2208,7 @@ async def test_export_tools_async(
transport: str = "grpc_asyncio", request_type=tool.ExportToolsRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2162,7 +2271,7 @@ def test_export_tools_field_headers():
@pytest.mark.asyncio
async def test_export_tools_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2233,6 +2342,25 @@ def test_get_tool(request_type, transport: str = "grpc"):
assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL
+def test_get_tool_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_tool), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.GetToolRequest()
+
+
def test_get_tool_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2296,13 +2424,39 @@ def test_get_tool_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_tool_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_tool), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ tool.Tool(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL,
+ )
+ )
+ response = await client.get_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.GetToolRequest()
+
+
@pytest.mark.asyncio
async def test_get_tool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2317,23 +2471,27 @@ async def test_get_tool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_tool
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_tool(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2341,7 +2499,7 @@ async def test_get_tool_async(
transport: str = "grpc_asyncio", request_type=tool.GetToolRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2413,7 +2571,7 @@ def test_get_tool_field_headers():
@pytest.mark.asyncio
async def test_get_tool_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2481,7 +2639,7 @@ def test_get_tool_flattened_error():
@pytest.mark.asyncio
async def test_get_tool_flattened_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2508,7 +2666,7 @@ async def test_get_tool_flattened_async():
@pytest.mark.asyncio
async def test_get_tool_flattened_error_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2562,6 +2720,25 @@ def test_update_tool(request_type, transport: str = "grpc"):
assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
+def test_update_tool_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_tool), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_tool.UpdateToolRequest()
+
+
def test_update_tool_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2621,6 +2798,32 @@ def test_update_tool_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_tool_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_tool), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_tool.Tool(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
+ )
+ )
+ response = await client.update_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_tool.UpdateToolRequest()
+
+
@pytest.mark.asyncio
async def test_update_tool_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2629,7 +2832,7 @@ async def test_update_tool_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2644,23 +2847,27 @@ async def test_update_tool_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_tool
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_tool(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2668,7 +2875,7 @@ async def test_update_tool_async(
transport: str = "grpc_asyncio", request_type=gcdc_tool.UpdateToolRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2740,7 +2947,7 @@ def test_update_tool_field_headers():
@pytest.mark.asyncio
async def test_update_tool_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2813,7 +3020,7 @@ def test_update_tool_flattened_error():
@pytest.mark.asyncio
async def test_update_tool_flattened_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2844,7 +3051,7 @@ async def test_update_tool_flattened_async():
@pytest.mark.asyncio
async def test_update_tool_flattened_error_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2890,6 +3097,25 @@ def test_delete_tool(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_tool_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 = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_tool), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.DeleteToolRequest()
+
+
def test_delete_tool_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2954,14 +3180,33 @@ def test_delete_tool_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_delete_tool_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
-):
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+async def test_delete_tool_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_tool), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_tool()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tool.DeleteToolRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_tool_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2976,23 +3221,27 @@ async def test_delete_tool_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_tool
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_tool(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3000,7 +3249,7 @@ async def test_delete_tool_async(
transport: str = "grpc_asyncio", request_type=tool.DeleteToolRequest
):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3061,7 +3310,7 @@ def test_delete_tool_field_headers():
@pytest.mark.asyncio
async def test_delete_tool_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3129,7 +3378,7 @@ def test_delete_tool_flattened_error():
@pytest.mark.asyncio
async def test_delete_tool_flattened_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3156,7 +3405,7 @@ async def test_delete_tool_flattened_async():
@pytest.mark.asyncio
async def test_delete_tool_flattened_error_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3168,6 +3417,155 @@ async def test_delete_tool_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_tool.CreateToolRequest,
+ dict,
+ ],
+)
+def test_create_tool_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["tool"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "open_api_spec": {
+ "text_schema": "text_schema_value",
+ "authentication": {
+ "api_key_config": {
+ "key_name": "key_name_value",
+ "api_key": "api_key_value",
+ "request_location": 1,
+ },
+ "oauth_config": {
+ "oauth_grant_type": 1,
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ },
+ "service_agent_auth_config": {},
+ },
+ "tls_config": {
+ "ca_certs": [
+ {"display_name": "display_name_value", "cert": b"cert_blob"}
+ ]
+ },
+ },
+ "data_store_spec": {
+ "data_store_connections": [
+ {"data_store_type": 1, "data_store": "data_store_value"}
+ ],
+ "fallback_prompt": {},
+ },
+ "extension_spec": {"name": "name_value"},
+ "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}},
+ "tool_type": 1,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_tool.CreateToolRequest.meta.fields["tool"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["tool"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["tool"][field])):
+ del request_init["tool"][field][i][subfield]
+ else:
+ del request_init["tool"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_tool.Tool(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_tool.Tool.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_tool(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_tool.Tool)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
+
+
def test_create_tool_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3294,6 +3692,81 @@ def test_create_tool_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_tool_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
+ )
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ToolsRestInterceptor, "post_create_tool"
+ ) as post, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_create_tool"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_tool.CreateToolRequest.pb(gcdc_tool.CreateToolRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_tool.Tool.to_json(gcdc_tool.Tool())
+
+ request = gcdc_tool.CreateToolRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_tool.Tool()
+
+ client.create_tool(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_tool_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_tool.CreateToolRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_tool(request)
+
+
def test_create_tool_rest_flattened():
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3353,16 +3826,62 @@ def test_create_tool_rest_flattened_error(transport: str = "rest"):
)
-def test_list_tools_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_create_tool_rest_error():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ tool.ListToolsRequest,
+ dict,
+ ],
+)
+def test_list_tools_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = tool.ListToolsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = tool.ListToolsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_tools(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListToolsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_tools_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
assert wrapper_fn.call_count > 0
wrapper_fn.reset_mock()
@@ -3485,6 +4004,83 @@ def test_list_tools_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_tools_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
+ )
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ToolsRestInterceptor, "post_list_tools"
+ ) as post, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_list_tools"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = tool.ListToolsRequest.pb(tool.ListToolsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = tool.ListToolsResponse.to_json(
+ tool.ListToolsResponse()
+ )
+
+ request = tool.ListToolsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = tool.ListToolsResponse()
+
+ client.list_tools(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_tools_rest_bad_request(
+ transport: str = "rest", request_type=tool.ListToolsRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_tools(request)
+
+
def test_list_tools_rest_flattened():
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3603,6 +4199,41 @@ def test_list_tools_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ tool.ExportToolsRequest,
+ dict,
+ ],
+)
+def test_export_tools_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.export_tools(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
def test_export_tools_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3734,144 +4365,119 @@ def test_export_tools_rest_unset_required_fields():
)
-def test_get_tool_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_export_tools_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
+ )
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.ToolsRestInterceptor, "post_export_tools"
+ ) as post, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_export_tools"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = tool.ExportToolsRequest.pb(tool.ExportToolsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
- # Ensure method has been cached
- assert client._transport.get_tool in client._transport._wrapped_methods
+ request = tool.ExportToolsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.export_tools(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc
- request = {}
- client.get_tool(request)
+ pre.assert_called_once()
+ post.assert_called_once()
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
- client.get_tool(request)
+def test_export_tools_rest_bad_request(
+ transport: str = "rest", request_type=tool.ExportToolsRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.export_tools(request)
-def test_get_tool_rest_required_fields(request_type=tool.GetToolRequest):
- transport_class = transports.ToolsRestTransport
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+def test_export_tools_rest_error():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_tool._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_tool._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ tool.GetToolRequest,
+ dict,
+ ],
+)
+def test_get_tool_rest(request_type):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = tool.Tool()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "get",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = tool.Tool.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.get_tool(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_tool_rest_unset_required_fields():
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_tool._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-def test_get_tool_rest_flattened():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = tool.Tool()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
+ return_value = tool.Tool(
name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL,
)
- mock_args.update(sample_request)
# Wrap the value into a proper Response obj
response_value = Response()
@@ -3879,38 +4485,20 @@ def test_get_tool_rest_flattened():
# Convert return value to protobuf type
return_value = tool.Tool.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
+
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
+ response = client.get_tool(request)
- client.get_tool(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_tool_rest_flattened_error(transport: str = "rest"):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_tool(
- tool.GetToolRequest(),
- name="name_value",
- )
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, tool.Tool)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL
-def test_update_tool_rest_use_cached_wrapped_rpc():
+def test_get_tool_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -3924,32 +4512,33 @@ def test_update_tool_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.update_tool in client._transport._wrapped_methods
+ assert client._transport.get_tool in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc
+ client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc
request = {}
- client.update_tool(request)
+ client.get_tool(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_tool(request)
+ client.get_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolRequest):
+def test_get_tool_rest_required_fields(request_type=tool.GetToolRequest):
transport_class = transports.ToolsRestTransport
request_init = {}
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -3960,19 +4549,21 @@ def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolReque
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_tool._get_unset_required_fields(jsonified_request)
+ ).get_tool._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ jsonified_request["name"] = "name_value"
+
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).update_tool._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("update_mask",))
+ ).get_tool._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3981,7 +4572,7 @@ def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolReque
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = gcdc_tool.Tool()
+ return_value = tool.Tool()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -3993,39 +4584,115 @@ def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolReque
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "patch",
+ "method": "get",
"query_params": pb_request,
}
- transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcdc_tool.Tool.pb(return_value)
+ return_value = tool.Tool.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.update_tool(request)
+ response = client.get_tool(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_update_tool_rest_unset_required_fields():
+def test_get_tool_rest_unset_required_fields():
transport = transports.ToolsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.update_tool._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("tool",)))
+ unset_fields = transport.get_tool._get_unset_required_fields({})
+ assert set(unset_fields) == (set(()) & set(("name",)))
-def test_update_tool_rest_flattened():
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_tool_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
+ )
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ToolsRestInterceptor, "post_get_tool"
+ ) as post, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_get_tool"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = tool.GetToolRequest.pb(tool.GetToolRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = tool.Tool.to_json(tool.Tool())
+
+ request = tool.GetToolRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = tool.Tool()
+
+ client.get_tool(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_tool_rest_bad_request(
+ transport: str = "rest", request_type=tool.GetToolRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_tool(request)
+
+
+def test_get_tool_rest_flattened():
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -4034,19 +4701,16 @@ def test_update_tool_rest_flattened():
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = gcdc_tool.Tool()
+ return_value = tool.Tool()
# get arguments that satisfy an http rule for this method
sample_request = {
- "tool": {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
}
# get truthy value for each flattened field
mock_args = dict(
- tool=gcdc_tool.Tool(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ name="name_value",
)
mock_args.update(sample_request)
@@ -4054,25 +4718,25 @@ def test_update_tool_rest_flattened():
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcdc_tool.Tool.pb(return_value)
+ return_value = tool.Tool.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.update_tool(**mock_args)
+ client.get_tool(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{tool.name=projects/*/locations/*/agents/*/tools/*}"
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}"
% client.transport._host,
args[1],
)
-def test_update_tool_rest_flattened_error(transport: str = "rest"):
+def test_get_tool_rest_flattened_error(transport: str = "rest"):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4081,14 +4745,172 @@ def test_update_tool_rest_flattened_error(transport: str = "rest"):
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.update_tool(
- gcdc_tool.UpdateToolRequest(),
- tool=gcdc_tool.Tool(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client.get_tool(
+ tool.GetToolRequest(),
+ name="name_value",
)
-def test_delete_tool_rest_use_cached_wrapped_rpc():
+def test_get_tool_rest_error():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_tool.UpdateToolRequest,
+ dict,
+ ],
+)
+def test_update_tool_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "tool": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+ }
+ request_init["tool"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "open_api_spec": {
+ "text_schema": "text_schema_value",
+ "authentication": {
+ "api_key_config": {
+ "key_name": "key_name_value",
+ "api_key": "api_key_value",
+ "request_location": 1,
+ },
+ "oauth_config": {
+ "oauth_grant_type": 1,
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ },
+ "service_agent_auth_config": {},
+ },
+ "tls_config": {
+ "ca_certs": [
+ {"display_name": "display_name_value", "cert": b"cert_blob"}
+ ]
+ },
+ },
+ "data_store_spec": {
+ "data_store_connections": [
+ {"data_store_type": 1, "data_store": "data_store_value"}
+ ],
+ "fallback_prompt": {},
+ },
+ "extension_spec": {"name": "name_value"},
+ "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}},
+ "tool_type": 1,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_tool.UpdateToolRequest.meta.fields["tool"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["tool"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["tool"][field])):
+ del request_init["tool"][field][i][subfield]
+ else:
+ del request_init["tool"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_tool.Tool(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_tool.Tool.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_tool(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_tool.Tool)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
+
+
+def test_update_tool_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -4102,33 +4924,32 @@ def test_delete_tool_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.delete_tool in client._transport._wrapped_methods
+ assert client._transport.update_tool in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc
+ client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc
request = {}
- client.delete_tool(request)
+ client.update_tool(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.delete_tool(request)
+ client.update_tool(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest):
+def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolRequest):
transport_class = transports.ToolsRestTransport
request_init = {}
- request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -4139,23 +4960,19 @@ def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest):
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_tool._get_unset_required_fields(jsonified_request)
+ ).update_tool._get_unset_required_fields(jsonified_request)
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- jsonified_request["name"] = "name_value"
-
unset_fields = transport_class(
credentials=ga_credentials.AnonymousCredentials()
- ).delete_tool._get_unset_required_fields(jsonified_request)
+ ).update_tool._get_unset_required_fields(jsonified_request)
# Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("force",))
+ assert not set(unset_fields) - set(("update_mask",))
jsonified_request.update(unset_fields)
# verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4164,7 +4981,7 @@ def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest):
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = None
+ return_value = gcdc_tool.Tool()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -4176,1479 +4993,104 @@ def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest):
pb_request = request_type.pb(request)
transcode_result = {
"uri": "v1/sample_method",
- "method": "delete",
+ "method": "patch",
"query_params": pb_request,
}
+ transcode_result["body"] = pb_request
transcode.return_value = transcode_result
response_value = Response()
response_value.status_code = 200
- json_return_value = ""
+
+ # Convert return value to protobuf type
+ return_value = gcdc_tool.Tool.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.delete_tool(request)
+ response = client.update_tool(request)
expected_params = [("$alt", "json;enum-encoding=int")]
actual_params = req.call_args.kwargs["params"]
assert expected_params == actual_params
-def test_delete_tool_rest_unset_required_fields():
+def test_update_tool_rest_unset_required_fields():
transport = transports.ToolsRestTransport(
credentials=ga_credentials.AnonymousCredentials
)
- unset_fields = transport.delete_tool._get_unset_required_fields({})
- assert set(unset_fields) == (set(("force",)) & set(("name",)))
+ unset_fields = transport.update_tool._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("updateMask",)) & set(("tool",)))
-def test_delete_tool_rest_flattened():
- client = ToolsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_tool_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
)
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ToolsRestInterceptor, "post_update_tool"
+ ) as post, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_update_tool"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_tool.UpdateToolRequest.pb(gcdc_tool.UpdateToolRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_tool.Tool.to_json(gcdc_tool.Tool())
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
+ request = gcdc_tool.UpdateToolRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_tool.Tool()
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_tool(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_tool_rest_flattened_error(transport: str = "rest"):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_tool(
- tool.DeleteToolRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ToolsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ToolsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ToolsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ToolsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = ToolsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ToolsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.ToolsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.ToolsGrpcTransport,
- transports.ToolsGrpcAsyncIOTransport,
- transports.ToolsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = ToolsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_tool_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_tool), "__call__") as call:
- call.return_value = gcdc_tool.Tool()
- client.create_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.CreateToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_tools_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_tools), "__call__") as call:
- call.return_value = tool.ListToolsResponse()
- client.list_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ListToolsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_tools_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_tools), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.export_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ExportToolsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_tool_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_tool), "__call__") as call:
- call.return_value = tool.Tool()
- client.get_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.GetToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_tool_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_tool), "__call__") as call:
- call.return_value = gcdc_tool.Tool()
- client.update_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.UpdateToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_tool_empty_call_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_tool), "__call__") as call:
- call.return_value = None
- client.delete_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.DeleteToolRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ToolsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_tool_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_tool), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
- )
- await client.create_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.CreateToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_tools_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_tools), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- tool.ListToolsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ListToolsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_export_tools_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_tools), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
- )
- await client.export_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ExportToolsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_tool_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_tool), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
- )
- await client.get_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.GetToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_tool_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_tool), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
- )
- await client.update_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.UpdateToolRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_tool_empty_call_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_tool), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.DeleteToolRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = ToolsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_create_tool_rest_bad_request(request_type=gcdc_tool.CreateToolRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_tool(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_tool.CreateToolRequest,
- dict,
- ],
-)
-def test_create_tool_rest_call_success(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["tool"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "description": "description_value",
- "open_api_spec": {
- "text_schema": "text_schema_value",
- "authentication": {
- "api_key_config": {
- "key_name": "key_name_value",
- "api_key": "api_key_value",
- "request_location": 1,
- },
- "oauth_config": {
- "oauth_grant_type": 1,
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- },
- "service_agent_auth_config": {},
- },
- "tls_config": {
- "ca_certs": [
- {"display_name": "display_name_value", "cert": b"cert_blob"}
- ]
- },
- "service_directory_config": {"service": "service_value"},
- },
- "data_store_spec": {
- "data_store_connections": [
- {"data_store_type": 1, "data_store": "data_store_value"}
- ],
- "fallback_prompt": {},
- },
- "extension_spec": {"name": "name_value"},
- "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}},
- "tool_type": 1,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_tool.CreateToolRequest.meta.fields["tool"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["tool"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["tool"][field])):
- del request_init["tool"][field][i][subfield]
- else:
- del request_init["tool"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_tool.Tool.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_tool(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_tool.Tool)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_tool_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ToolsRestInterceptor, "post_create_tool"
- ) as post, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_create_tool"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_tool.CreateToolRequest.pb(gcdc_tool.CreateToolRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_tool.Tool.to_json(gcdc_tool.Tool())
- req.return_value.content = return_value
-
- request = gcdc_tool.CreateToolRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_tool.Tool()
-
- client.create_tool(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_tools_rest_bad_request(request_type=tool.ListToolsRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_tools(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- tool.ListToolsRequest,
- dict,
- ],
-)
-def test_list_tools_rest_call_success(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = tool.ListToolsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = tool.ListToolsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_tools(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListToolsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_tools_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ToolsRestInterceptor, "post_list_tools"
- ) as post, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_list_tools"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = tool.ListToolsRequest.pb(tool.ListToolsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = tool.ListToolsResponse.to_json(tool.ListToolsResponse())
- req.return_value.content = return_value
-
- request = tool.ListToolsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = tool.ListToolsResponse()
-
- client.list_tools(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_export_tools_rest_bad_request(request_type=tool.ExportToolsRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.export_tools(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- tool.ExportToolsRequest,
- dict,
- ],
-)
-def test_export_tools_rest_call_success(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.export_tools(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_export_tools_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.ToolsRestInterceptor, "post_export_tools"
- ) as post, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_export_tools"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = tool.ExportToolsRequest.pb(tool.ExportToolsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = tool.ExportToolsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.export_tools(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_tool_rest_bad_request(request_type=tool.GetToolRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_tool(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- tool.GetToolRequest,
- dict,
- ],
-)
-def test_get_tool_rest_call_success(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = tool.Tool.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_tool(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, tool.Tool)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_tool_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ToolsRestInterceptor, "post_get_tool"
- ) as post, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_get_tool"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = tool.GetToolRequest.pb(tool.GetToolRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = tool.Tool.to_json(tool.Tool())
- req.return_value.content = return_value
-
- request = tool.GetToolRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = tool.Tool()
-
- client.get_tool(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_tool_rest_bad_request(request_type=gcdc_tool.UpdateToolRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "tool": {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_tool(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_tool.UpdateToolRequest,
- dict,
- ],
-)
-def test_update_tool_rest_call_success(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "tool": {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- }
- request_init["tool"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4",
- "display_name": "display_name_value",
- "description": "description_value",
- "open_api_spec": {
- "text_schema": "text_schema_value",
- "authentication": {
- "api_key_config": {
- "key_name": "key_name_value",
- "api_key": "api_key_value",
- "request_location": 1,
- },
- "oauth_config": {
- "oauth_grant_type": 1,
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- },
- "service_agent_auth_config": {},
- },
- "tls_config": {
- "ca_certs": [
- {"display_name": "display_name_value", "cert": b"cert_blob"}
- ]
- },
- "service_directory_config": {"service": "service_value"},
- },
- "data_store_spec": {
- "data_store_connections": [
- {"data_store_type": 1, "data_store": "data_store_value"}
- ],
- "fallback_prompt": {},
- },
- "extension_spec": {"name": "name_value"},
- "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}},
- "tool_type": 1,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_tool.UpdateToolRequest.meta.fields["tool"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["tool"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["tool"][field])):
- del request_init["tool"][field][i][subfield]
- else:
- del request_init["tool"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_tool.Tool(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_tool.Tool.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_tool(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_tool.Tool)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_tool_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ToolsRestInterceptor, "post_update_tool"
- ) as post, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_update_tool"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_tool.UpdateToolRequest.pb(gcdc_tool.UpdateToolRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_tool.Tool.to_json(gcdc_tool.Tool())
- req.return_value.content = return_value
-
- request = gcdc_tool.UpdateToolRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_tool.Tool()
-
- client.update_tool(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ client.update_tool(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
pre.assert_called_once()
post.assert_called_once()
-def test_delete_tool_rest_bad_request(request_type=tool.DeleteToolRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_tool(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- tool.DeleteToolRequest,
- dict,
- ],
-)
-def test_delete_tool_rest_call_success(request_type):
+def test_update_tool_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_tool.UpdateToolRequest
+):
client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_tool(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_tool_rest_interceptors(null_interceptor):
- transport = transports.ToolsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
- )
- client = ToolsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.ToolsRestInterceptor, "pre_delete_tool"
- ) as pre:
- pre.assert_not_called()
- pb_message = tool.DeleteToolRequest.pb(tool.DeleteToolRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
+ "tool": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
}
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = tool.DeleteToolRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_tool(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -5656,177 +5098,292 @@ def test_list_locations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_locations(request)
+ client.update_tool(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
+def test_update_tool_rest_flattened():
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ return_value = gcdc_tool.Tool()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "tool": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ tool=gcdc_tool.Tool(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_tool.Tool.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_locations(request)
+ client.update_tool(**mock_args)
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{tool.name=projects/*/locations/*/agents/*/tools/*}"
+ % client.transport._host,
+ args[1],
+ )
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
+def test_update_tool_rest_flattened_error(transport: str = "rest"):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport=transport,
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_tool(
+ gcdc_tool.UpdateToolRequest(),
+ tool=gcdc_tool.Tool(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_update_tool_rest_error():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- operations_pb2.CancelOperationRequest,
+ tool.DeleteToolRequest,
dict,
],
)
-def test_cancel_operation_rest(request_type):
+def test_delete_tool_rest(request_type):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/operations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
return_value = None
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.cancel_operation(request)
+ response = client.delete_tool(request)
# Establish that the response is the type that we expect.
assert response is None
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_delete_tool_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_tool in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc
+
+ request = {}
+ client.delete_tool(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_tool(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest):
+ transport_class = transports.ToolsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_tool._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_tool._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("force",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1/operations/sample2"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "delete",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.delete_tool(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_delete_tool_rest_unset_required_fields():
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.delete_tool._get_unset_required_fields({})
+ assert set(unset_fields) == (set(("force",)) & set(("name",)))
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_tool_rest_interceptors(null_interceptor):
+ transport = transports.ToolsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.ToolsRestInterceptor(),
+ )
+ client = ToolsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.ToolsRestInterceptor, "pre_delete_tool"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = tool.DeleteToolRequest.pb(tool.DeleteToolRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- req.return_value = response_value
+ request = tool.DeleteToolRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- response = client.get_operation(request)
+ client.delete_tool(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_delete_tool_rest_bad_request(
+ transport: str = "rest", request_type=tool.DeleteToolRequest
):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -5834,190 +5391,179 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
+ client.delete_tool(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+def test_delete_tool_rest_flattened():
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ return_value = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
+ client.delete_tool(**mock_args)
-def test_initialize_client_w_rest():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/tools/*}"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_tool_empty_call_rest():
+def test_delete_tool_rest_flattened_error(transport: str = "rest"):
client = ToolsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_tool), "__call__") as call:
- client.create_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.CreateToolRequest()
-
- assert args[0] == request_msg
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_tool(
+ tool.DeleteToolRequest(),
+ name="name_value",
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_tools_empty_call_rest():
+def test_delete_tool_rest_error():
client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_tools), "__call__") as call:
- client.list_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ListToolsRequest()
-
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_export_tools_empty_call_rest():
- client = ToolsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.ToolsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.export_tools), "__call__") as call:
- client.export_tools(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.ExportToolsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_tool_empty_call_rest():
- client = ToolsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ToolsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = ToolsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_tool), "__call__") as call:
- client.get_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.GetToolRequest()
-
- assert args[0] == request_msg
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.ToolsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ToolsClient(
+ client_options=options,
+ transport=transport,
+ )
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ToolsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_tool_empty_call_rest():
- client = ToolsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ToolsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = ToolsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_tool), "__call__") as call:
- client.update_tool(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_tool.UpdateToolRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ToolsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = ToolsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_tool_empty_call_rest():
- client = ToolsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ToolsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_tool), "__call__") as call:
- client.delete_tool(request=None)
+ transport = transports.ToolsGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = tool.DeleteToolRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ToolsGrpcTransport,
+ transports.ToolsGrpcAsyncIOTransport,
+ transports.ToolsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_tools_rest_lro_client():
- client = ToolsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = ToolsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6262,15 +5808,32 @@ def test_tools_grpc_transport_client_cert_source_for_mtls(transport_class):
)
-def test_tools_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.ToolsRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_tools_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.ToolsRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_tools_rest_lro_client():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -6508,40 +6071,11 @@ def test_tools_grpc_lro_async_client():
assert transport.operations_client is transport.operations_client
-def test_service_path():
+def test_tool_path():
project = "squid"
location = "clam"
- namespace = "whelk"
- service = "octopus"
- expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(
- project=project,
- location=location,
- namespace=namespace,
- service=service,
- )
- actual = ToolsClient.service_path(project, location, namespace, service)
- assert expected == actual
-
-
-def test_parse_service_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- "namespace": "cuttlefish",
- "service": "mussel",
- }
- path = ToolsClient.service_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_service_path(path)
- assert expected == actual
-
-
-def test_tool_path():
- project = "winkle"
- location = "nautilus"
- agent = "scallop"
- tool = "abalone"
+ agent = "whelk"
+ tool = "octopus"
expected = (
"projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format(
project=project,
@@ -6556,10 +6090,10 @@ def test_tool_path():
def test_parse_tool_path():
expected = {
- "project": "squid",
- "location": "clam",
- "agent": "whelk",
- "tool": "octopus",
+ "project": "oyster",
+ "location": "nudibranch",
+ "agent": "cuttlefish",
+ "tool": "mussel",
}
path = ToolsClient.tool_path(**expected)
@@ -6569,7 +6103,7 @@ def test_parse_tool_path():
def test_common_billing_account_path():
- billing_account = "oyster"
+ billing_account = "winkle"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -6577,117 +6111,417 @@ def test_common_billing_account_path():
assert expected == actual
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "nudibranch",
- }
- path = ToolsClient.common_billing_account_path(**expected)
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nautilus",
+ }
+ path = ToolsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ToolsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = ToolsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = ToolsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ToolsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = ToolsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = ToolsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ToolsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = ToolsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = ToolsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ToolsClient.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 = ToolsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = ToolsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ToolsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep:
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep:
+ transport_class = ToolsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = ToolsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ToolsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = ToolsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ToolsClient.common_organization_path(organization)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = ToolsClient.common_organization_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = ToolsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = ToolsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ToolsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = ToolsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = ToolsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep:
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep:
- transport_class = ToolsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6717,7 +6551,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6770,7 +6604,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6815,7 +6649,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6856,7 +6690,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6911,7 +6745,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6958,7 +6792,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -7001,7 +6835,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7056,7 +6890,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7103,7 +6937,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -7146,7 +6980,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7201,7 +7035,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7248,7 +7082,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7291,7 +7125,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7343,7 +7177,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = ToolsAsyncClient(credentials=async_anonymous_credentials())
+ client = ToolsAsyncClient(credentials=ga_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.
@@ -7389,7 +7223,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7405,41 +7239,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = ToolsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = ToolsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = ToolsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py
index 44720b29b608..7a3e17920cb3 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -55,7 +37,15 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import (
TransitionRouteGroupsAsyncClient,
@@ -77,24 +67,10 @@
from google.cloud.dialogflowcx_v3beta1.types import transition_route_group
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1267,6 +1243,27 @@ def test_list_transition_route_groups(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_transition_route_groups_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 = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_transition_route_groups), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_transition_route_groups()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest()
+
+
def test_list_transition_route_groups_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1341,6 +1338,31 @@ def test_list_transition_route_groups_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_transition_route_groups_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_transition_route_groups), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ transition_route_group.ListTransitionRouteGroupsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_transition_route_groups()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest()
+
+
@pytest.mark.asyncio
async def test_list_transition_route_groups_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1349,7 +1371,7 @@ async def test_list_transition_route_groups_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1364,23 +1386,27 @@ async def test_list_transition_route_groups_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_transition_route_groups
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_transition_route_groups(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_transition_route_groups(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1389,7 +1415,7 @@ async def test_list_transition_route_groups_async(
request_type=transition_route_group.ListTransitionRouteGroupsRequest,
):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1459,7 +1485,7 @@ def test_list_transition_route_groups_field_headers():
@pytest.mark.asyncio
async def test_list_transition_route_groups_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1533,7 +1559,7 @@ def test_list_transition_route_groups_flattened_error():
@pytest.mark.asyncio
async def test_list_transition_route_groups_flattened_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1564,7 +1590,7 @@ async def test_list_transition_route_groups_flattened_async():
@pytest.mark.asyncio
async def test_list_transition_route_groups_flattened_error_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1616,18 +1642,12 @@ def test_list_transition_route_groups_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_transition_route_groups(
- request={}, retry=retry, timeout=timeout
- )
+ pager = client.list_transition_route_groups(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1682,7 +1702,7 @@ def test_list_transition_route_groups_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_transition_route_groups_async_pager():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1737,7 +1757,7 @@ async def test_list_transition_route_groups_async_pager():
@pytest.mark.asyncio
async def test_list_transition_route_groups_async_pages():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1825,6 +1845,27 @@ def test_get_transition_route_group(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_get_transition_route_group_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 = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_transition_route_group), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.GetTransitionRouteGroupRequest()
+
+
def test_get_transition_route_group_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1897,6 +1938,32 @@ def test_get_transition_route_group_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_transition_route_group_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_transition_route_group), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ transition_route_group.TransitionRouteGroup(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.get_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.GetTransitionRouteGroupRequest()
+
+
@pytest.mark.asyncio
async def test_get_transition_route_group_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1905,7 +1972,7 @@ async def test_get_transition_route_group_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1920,23 +1987,27 @@ async def test_get_transition_route_group_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_transition_route_group
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_transition_route_group(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_transition_route_group(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1945,7 +2016,7 @@ async def test_get_transition_route_group_async(
request_type=transition_route_group.GetTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2017,7 +2088,7 @@ def test_get_transition_route_group_field_headers():
@pytest.mark.asyncio
async def test_get_transition_route_group_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2091,7 +2162,7 @@ def test_get_transition_route_group_flattened_error():
@pytest.mark.asyncio
async def test_get_transition_route_group_flattened_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2122,7 +2193,7 @@ async def test_get_transition_route_group_flattened_async():
@pytest.mark.asyncio
async def test_get_transition_route_group_flattened_error_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2174,6 +2245,29 @@ def test_create_transition_route_group(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_create_transition_route_group_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 = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_transition_route_group), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert (
+ args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
+ )
+
+
def test_create_transition_route_group_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2246,6 +2340,34 @@ def test_create_transition_route_group_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_transition_route_group_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_transition_route_group), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_transition_route_group.TransitionRouteGroup(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.create_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert (
+ args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
+ )
+
+
@pytest.mark.asyncio
async def test_create_transition_route_group_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2254,7 +2376,7 @@ async def test_create_transition_route_group_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2269,23 +2391,27 @@ async def test_create_transition_route_group_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_transition_route_group
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_transition_route_group(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_transition_route_group(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2294,7 +2420,7 @@ async def test_create_transition_route_group_async(
request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2366,7 +2492,7 @@ def test_create_transition_route_group_field_headers():
@pytest.mark.asyncio
async def test_create_transition_route_group_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2449,7 +2575,7 @@ def test_create_transition_route_group_flattened_error():
@pytest.mark.asyncio
async def test_create_transition_route_group_flattened_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2486,7 +2612,7 @@ async def test_create_transition_route_group_flattened_async():
@pytest.mark.asyncio
async def test_create_transition_route_group_flattened_error_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2541,6 +2667,29 @@ def test_update_transition_route_group(request_type, transport: str = "grpc"):
assert response.display_name == "display_name_value"
+def test_update_transition_route_group_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 = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_transition_route_group), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert (
+ args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
+ )
+
+
def test_update_transition_route_group_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2611,6 +2760,34 @@ def test_update_transition_route_group_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_transition_route_group_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_transition_route_group), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_transition_route_group.TransitionRouteGroup(
+ name="name_value",
+ display_name="display_name_value",
+ )
+ )
+ response = await client.update_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert (
+ args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
+ )
+
+
@pytest.mark.asyncio
async def test_update_transition_route_group_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2619,7 +2796,7 @@ async def test_update_transition_route_group_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2634,23 +2811,27 @@ async def test_update_transition_route_group_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_transition_route_group
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_transition_route_group(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_transition_route_group(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2659,7 +2840,7 @@ async def test_update_transition_route_group_async(
request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2731,7 +2912,7 @@ def test_update_transition_route_group_field_headers():
@pytest.mark.asyncio
async def test_update_transition_route_group_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2814,7 +2995,7 @@ def test_update_transition_route_group_flattened_error():
@pytest.mark.asyncio
async def test_update_transition_route_group_flattened_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2851,7 +3032,7 @@ async def test_update_transition_route_group_flattened_async():
@pytest.mark.asyncio
async def test_update_transition_route_group_flattened_error_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2901,6 +3082,27 @@ def test_delete_transition_route_group(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_transition_route_group_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 = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_transition_route_group), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest()
+
+
def test_delete_transition_route_group_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2971,6 +3173,27 @@ def test_delete_transition_route_group_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_transition_route_group_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_transition_route_group), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_transition_route_group()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest()
+
+
@pytest.mark.asyncio
async def test_delete_transition_route_group_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2979,7 +3202,7 @@ async def test_delete_transition_route_group_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2994,23 +3217,27 @@ async def test_delete_transition_route_group_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_transition_route_group
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_transition_route_group(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_transition_route_group(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3019,7 +3246,7 @@ async def test_delete_transition_route_group_async(
request_type=transition_route_group.DeleteTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3084,7 +3311,7 @@ def test_delete_transition_route_group_field_headers():
@pytest.mark.asyncio
async def test_delete_transition_route_group_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3156,7 +3383,7 @@ def test_delete_transition_route_group_flattened_error():
@pytest.mark.asyncio
async def test_delete_transition_route_group_flattened_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3185,7 +3412,7 @@ async def test_delete_transition_route_group_flattened_async():
@pytest.mark.asyncio
async def test_delete_transition_route_group_flattened_error_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3197,6 +3424,50 @@ async def test_delete_transition_route_group_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ transition_route_group.ListTransitionRouteGroupsRequest,
+ dict,
+ ],
+)
+def test_list_transition_route_groups_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = transition_route_group.ListTransitionRouteGroupsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = transition_route_group.ListTransitionRouteGroupsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_transition_route_groups(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListTransitionRouteGroupsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
def test_list_transition_route_groups_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3340,6 +3611,94 @@ def test_list_transition_route_groups_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_transition_route_groups_rest_interceptors(null_interceptor):
+ transport = transports.TransitionRouteGroupsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.TransitionRouteGroupsRestInterceptor(),
+ )
+ client = TransitionRouteGroupsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "post_list_transition_route_groups",
+ ) as post, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "pre_list_transition_route_groups",
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = transition_route_group.ListTransitionRouteGroupsRequest.pb(
+ transition_route_group.ListTransitionRouteGroupsRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ transition_route_group.ListTransitionRouteGroupsResponse.to_json(
+ transition_route_group.ListTransitionRouteGroupsResponse()
+ )
+ )
+
+ request = transition_route_group.ListTransitionRouteGroupsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = transition_route_group.ListTransitionRouteGroupsResponse()
+
+ client.list_transition_route_groups(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_transition_route_groups_rest_bad_request(
+ transport: str = "rest",
+ request_type=transition_route_group.ListTransitionRouteGroupsRequest,
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_transition_route_groups(request)
+
+
def test_list_transition_route_groups_rest_flattened():
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3469,6 +3828,50 @@ def test_list_transition_route_groups_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ transition_route_group.GetTransitionRouteGroupRequest,
+ dict,
+ ],
+)
+def test_get_transition_route_group_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = transition_route_group.TransitionRouteGroup(
+ name="name_value",
+ display_name="display_name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = transition_route_group.TransitionRouteGroup.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_transition_route_group(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, transition_route_group.TransitionRouteGroup)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+
+
def test_get_transition_route_group_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3595,6 +3998,92 @@ def test_get_transition_route_group_rest_unset_required_fields():
assert set(unset_fields) == (set(("languageCode",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_transition_route_group_rest_interceptors(null_interceptor):
+ transport = transports.TransitionRouteGroupsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.TransitionRouteGroupsRestInterceptor(),
+ )
+ client = TransitionRouteGroupsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "post_get_transition_route_group",
+ ) as post, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "pre_get_transition_route_group",
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = transition_route_group.GetTransitionRouteGroupRequest.pb(
+ transition_route_group.GetTransitionRouteGroupRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = transition_route_group.TransitionRouteGroup.to_json(
+ transition_route_group.TransitionRouteGroup()
+ )
+
+ request = transition_route_group.GetTransitionRouteGroupRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = transition_route_group.TransitionRouteGroup()
+
+ client.get_transition_route_group(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_transition_route_group_rest_bad_request(
+ transport: str = "rest",
+ request_type=transition_route_group.GetTransitionRouteGroupRequest,
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_transition_route_group(request)
+
+
def test_get_transition_route_group_rest_flattened():
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3654,8 +4143,236 @@ def test_get_transition_route_group_rest_flattened_error(transport: str = "rest"
)
-def test_create_transition_route_group_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+def test_get_transition_route_group_rest_error():
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_transition_route_group.CreateTransitionRouteGroupRequest,
+ dict,
+ ],
+)
+def test_create_transition_route_group_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request_init["transition_route_group"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "transition_routes": [
+ {
+ "name": "name_value",
+ "description": "description_value",
+ "intent": "intent_value",
+ "condition": "condition_value",
+ "trigger_fulfillment": {
+ "messages": [
+ {
+ "text": {
+ "text": ["text_value1", "text_value2"],
+ "allow_playback_interruption": True,
+ },
+ "payload": {"fields": {}},
+ "conversation_success": {"metadata": {}},
+ "output_audio_text": {
+ "text": "text_value",
+ "ssml": "ssml_value",
+ "allow_playback_interruption": True,
+ },
+ "live_agent_handoff": {"metadata": {}},
+ "end_interaction": {},
+ "play_audio": {
+ "audio_uri": "audio_uri_value",
+ "allow_playback_interruption": True,
+ },
+ "mixed_audio": {
+ "segments": [
+ {
+ "audio": b"audio_blob",
+ "uri": "uri_value",
+ "allow_playback_interruption": True,
+ }
+ ]
+ },
+ "telephony_transfer_call": {
+ "phone_number": "phone_number_value"
+ },
+ "knowledge_info_card": {},
+ "tool_call": {
+ "tool": "tool_value",
+ "action": "action_value",
+ "input_parameters": {},
+ },
+ "channel": "channel_value",
+ }
+ ],
+ "webhook": "webhook_value",
+ "return_partial_responses": True,
+ "tag": "tag_value",
+ "set_parameter_actions": [
+ {
+ "parameter": "parameter_value",
+ "value": {
+ "null_value": 0,
+ "number_value": 0.1285,
+ "string_value": "string_value_value",
+ "bool_value": True,
+ "struct_value": {},
+ "list_value": {"values": {}},
+ },
+ }
+ ],
+ "conditional_cases": [
+ {
+ "cases": [
+ {
+ "condition": "condition_value",
+ "case_content": [
+ {"message": {}, "additional_cases": {}}
+ ],
+ }
+ ]
+ }
+ ],
+ "advanced_settings": {
+ "audio_export_gcs_destination": {"uri": "uri_value"},
+ "speech_settings": {
+ "endpointer_sensitivity": 2402,
+ "no_speech_timeout": {"seconds": 751, "nanos": 543},
+ "use_timeout_based_endpointing": True,
+ "models": {},
+ },
+ "dtmf_settings": {
+ "enabled": True,
+ "max_digits": 1065,
+ "finish_digit": "finish_digit_value",
+ "interdigit_timeout_duration": {},
+ "endpointing_timeout_duration": {},
+ },
+ "logging_settings": {
+ "enable_stackdriver_logging": True,
+ "enable_interaction_logging": True,
+ },
+ },
+ "enable_generative_fallback": True,
+ },
+ "target_page": "target_page_value",
+ "target_flow": "target_flow_value",
+ }
+ ],
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = (
+ gcdc_transition_route_group.CreateTransitionRouteGroupRequest.meta.fields[
+ "transition_route_group"
+ ]
+ )
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init[
+ "transition_route_group"
+ ].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["transition_route_group"][field])):
+ del request_init["transition_route_group"][field][i][subfield]
+ else:
+ del request_init["transition_route_group"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_transition_route_group.TransitionRouteGroup(
+ name="name_value",
+ display_name="display_name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_transition_route_group(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+
+
+def test_create_transition_route_group_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = TransitionRouteGroupsClient(
@@ -3793,211 +4510,95 @@ def test_create_transition_route_group_rest_unset_required_fields():
)
-def test_create_transition_route_group_rest_flattened():
- client = TransitionRouteGroupsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_transition_route_group_rest_interceptors(null_interceptor):
+ transport = transports.TransitionRouteGroupsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.TransitionRouteGroupsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_transition_route_group.TransitionRouteGroup()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
- name="name_value"
- ),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.create_transition_route_group(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/transitionRouteGroups"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_transition_route_group_rest_flattened_error(transport: str = "rest"):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_transition_route_group(
- gcdc_transition_route_group.CreateTransitionRouteGroupRequest(),
- parent="parent_value",
- transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
- name="name_value"
- ),
+ client = TransitionRouteGroupsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "post_create_transition_route_group",
+ ) as post, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "pre_create_transition_route_group",
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_transition_route_group.CreateTransitionRouteGroupRequest.pb(
+ gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
)
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
-
-def test_update_transition_route_group_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ gcdc_transition_route_group.TransitionRouteGroup.to_json(
+ gcdc_transition_route_group.TransitionRouteGroup()
+ )
)
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.update_transition_route_group
- in client._transport._wrapped_methods
- )
+ request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_transition_route_group.TransitionRouteGroup()
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ client.create_transition_route_group(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- client._transport._wrapped_methods[
- client._transport.update_transition_route_group
- ] = mock_rpc
-
- request = {}
- client.update_transition_route_group(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.update_transition_route_group(request)
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_update_transition_route_group_rest_required_fields(
- request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest,
+def test_create_transition_route_group_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest,
):
- transport_class = transports.TransitionRouteGroupsRestTransport
-
- request_init = {}
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_transition_route_group._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).update_transition_route_group._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "language_code",
- "update_mask",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
-
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = gcdc_transition_route_group.TransitionRouteGroup()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "patch",
- "query_params": pb_request,
- }
- transcode_result["body"] = pb_request
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(
- return_value
- )
- json_return_value = json_format.MessageToJson(return_value)
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.update_transition_route_group(request)
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_transition_route_group_rest_unset_required_fields():
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
- unset_fields = transport.update_transition_route_group._get_unset_required_fields(
- {}
- )
- assert set(unset_fields) == (
- set(
- (
- "languageCode",
- "updateMask",
- )
- )
- & set(("transitionRouteGroup",))
- )
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_transition_route_group(request)
-def test_update_transition_route_group_rest_flattened():
+def test_create_transition_route_group_rest_flattened():
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -4010,17 +4611,15 @@ def test_update_transition_route_group_rest_flattened():
# get arguments that satisfy an http rule for this method
sample_request = {
- "transition_route_group": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
}
# get truthy value for each flattened field
mock_args = dict(
+ parent="parent_value",
transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
name="name_value"
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
mock_args.update(sample_request)
@@ -4033,20 +4632,20 @@ def test_update_transition_route_group_rest_flattened():
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.update_transition_route_group(**mock_args)
+ client.create_transition_route_group(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, args, _ = req.mock_calls[0]
assert path_template.validate(
- "%s/v3beta1/{transition_route_group.name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}"
+ "%s/v3beta1/{parent=projects/*/locations/*/agents/*/flows/*}/transitionRouteGroups"
% client.transport._host,
args[1],
)
-def test_update_transition_route_group_rest_flattened_error(transport: str = "rest"):
+def test_create_transition_route_group_rest_flattened_error(transport: str = "rest"):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4055,1175 +4654,19 @@ def test_update_transition_route_group_rest_flattened_error(transport: str = "re
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.update_transition_route_group(
- gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(),
+ client.create_transition_route_group(
+ gcdc_transition_route_group.CreateTransitionRouteGroupRequest(),
+ parent="parent_value",
transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
name="name_value"
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
-def test_delete_transition_route_group_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert (
- client._transport.delete_transition_route_group
- in client._transport._wrapped_methods
- )
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[
- client._transport.delete_transition_route_group
- ] = mock_rpc
-
- request = {}
- client.delete_transition_route_group(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.delete_transition_route_group(request)
-
- # Establish that a new wrapper was not created for this call
- assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
-
-
-def test_delete_transition_route_group_rest_required_fields(
- request_type=transition_route_group.DeleteTransitionRouteGroupRequest,
-):
- transport_class = transports.TransitionRouteGroupsRestTransport
-
- request_init = {}
- request_init["name"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(pb_request, use_integers_for_enums=False)
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_transition_route_group._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
-
- jsonified_request["name"] = "name_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).delete_transition_route_group._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("force",))
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
-
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = None
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force all the
- # request fields to show up in the query_params.
- pb_request = request_type.pb(request)
- transcode_result = {
- "uri": "v1/sample_method",
- "method": "delete",
- "query_params": pb_request,
- }
- transcode.return_value = transcode_result
-
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
-
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- response = client.delete_transition_route_group(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_transition_route_group_rest_unset_required_fields():
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_transition_route_group._get_unset_required_fields(
- {}
- )
- assert set(unset_fields) == (set(("force",)) & set(("name",)))
-
-
-def test_delete_transition_route_group_rest_flattened():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = ""
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_transition_route_group(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_transition_route_group_rest_flattened_error(transport: str = "rest"):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_transition_route_group(
- transition_route_group.DeleteTransitionRouteGroupRequest(),
- name="name_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TransitionRouteGroupsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = TransitionRouteGroupsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = TransitionRouteGroupsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = TransitionRouteGroupsClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = TransitionRouteGroupsClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.TransitionRouteGroupsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.TransitionRouteGroupsGrpcTransport,
- transports.TransitionRouteGroupsGrpcAsyncIOTransport,
- transports.TransitionRouteGroupsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = TransitionRouteGroupsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_transition_route_groups_empty_call_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_transition_route_groups), "__call__"
- ) as call:
- call.return_value = transition_route_group.ListTransitionRouteGroupsResponse()
- client.list_transition_route_groups(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.ListTransitionRouteGroupsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_transition_route_group_empty_call_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_transition_route_group), "__call__"
- ) as call:
- call.return_value = transition_route_group.TransitionRouteGroup()
- client.get_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.GetTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_transition_route_group_empty_call_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_transition_route_group), "__call__"
- ) as call:
- call.return_value = gcdc_transition_route_group.TransitionRouteGroup()
- client.create_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_transition_route_group_empty_call_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_transition_route_group), "__call__"
- ) as call:
- call.return_value = gcdc_transition_route_group.TransitionRouteGroup()
- client.update_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_transition_route_group_empty_call_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_transition_route_group), "__call__"
- ) as call:
- call.return_value = None
- client.delete_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.DeleteTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = TransitionRouteGroupsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_transition_route_groups_empty_call_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_transition_route_groups), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- transition_route_group.ListTransitionRouteGroupsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_transition_route_groups(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.ListTransitionRouteGroupsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_transition_route_group_empty_call_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_transition_route_group), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- transition_route_group.TransitionRouteGroup(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.get_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.GetTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_transition_route_group_empty_call_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_transition_route_group), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_transition_route_group.TransitionRouteGroup(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.create_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_transition_route_group_empty_call_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_transition_route_group), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_transition_route_group.TransitionRouteGroup(
- name="name_value",
- display_name="display_name_value",
- )
- )
- await client.update_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_transition_route_group_empty_call_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_transition_route_group), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.DeleteTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = TransitionRouteGroupsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_transition_route_groups_rest_bad_request(
- request_type=transition_route_group.ListTransitionRouteGroupsRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_transition_route_groups(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- transition_route_group.ListTransitionRouteGroupsRequest,
- dict,
- ],
-)
-def test_list_transition_route_groups_rest_call_success(request_type):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = transition_route_group.ListTransitionRouteGroupsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = transition_route_group.ListTransitionRouteGroupsResponse.pb(
- return_value
- )
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_transition_route_groups(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListTransitionRouteGroupsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_transition_route_groups_rest_interceptors(null_interceptor):
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.TransitionRouteGroupsRestInterceptor(),
- )
- client = TransitionRouteGroupsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "post_list_transition_route_groups",
- ) as post, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "pre_list_transition_route_groups",
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = transition_route_group.ListTransitionRouteGroupsRequest.pb(
- transition_route_group.ListTransitionRouteGroupsRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = transition_route_group.ListTransitionRouteGroupsResponse.to_json(
- transition_route_group.ListTransitionRouteGroupsResponse()
- )
- req.return_value.content = return_value
-
- request = transition_route_group.ListTransitionRouteGroupsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = transition_route_group.ListTransitionRouteGroupsResponse()
-
- client.list_transition_route_groups(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_transition_route_group_rest_bad_request(
- request_type=transition_route_group.GetTransitionRouteGroupRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_transition_route_group(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- transition_route_group.GetTransitionRouteGroupRequest,
- dict,
- ],
-)
-def test_get_transition_route_group_rest_call_success(request_type):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = transition_route_group.TransitionRouteGroup(
- name="name_value",
- display_name="display_name_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = transition_route_group.TransitionRouteGroup.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_transition_route_group(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, transition_route_group.TransitionRouteGroup)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_transition_route_group_rest_interceptors(null_interceptor):
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.TransitionRouteGroupsRestInterceptor(),
- )
- client = TransitionRouteGroupsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "post_get_transition_route_group",
- ) as post, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "pre_get_transition_route_group",
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = transition_route_group.GetTransitionRouteGroupRequest.pb(
- transition_route_group.GetTransitionRouteGroupRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = transition_route_group.TransitionRouteGroup.to_json(
- transition_route_group.TransitionRouteGroup()
- )
- req.return_value.content = return_value
-
- request = transition_route_group.GetTransitionRouteGroupRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = transition_route_group.TransitionRouteGroup()
-
- client.get_transition_route_group(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_transition_route_group_rest_bad_request(
- request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_transition_route_group(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_transition_route_group.CreateTransitionRouteGroupRequest,
- dict,
- ],
-)
-def test_create_transition_route_group_rest_call_success(request_type):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request_init["transition_route_group"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "transition_routes": [
- {
- "name": "name_value",
- "description": "description_value",
- "intent": "intent_value",
- "condition": "condition_value",
- "trigger_fulfillment": {
- "messages": [
- {
- "text": {
- "text": ["text_value1", "text_value2"],
- "allow_playback_interruption": True,
- },
- "payload": {"fields": {}},
- "conversation_success": {"metadata": {}},
- "output_audio_text": {
- "text": "text_value",
- "ssml": "ssml_value",
- "allow_playback_interruption": True,
- },
- "live_agent_handoff": {"metadata": {}},
- "end_interaction": {},
- "play_audio": {
- "audio_uri": "audio_uri_value",
- "allow_playback_interruption": True,
- },
- "mixed_audio": {
- "segments": [
- {
- "audio": b"audio_blob",
- "uri": "uri_value",
- "allow_playback_interruption": True,
- }
- ]
- },
- "telephony_transfer_call": {
- "phone_number": "phone_number_value"
- },
- "knowledge_info_card": {},
- "tool_call": {
- "tool": "tool_value",
- "action": "action_value",
- "input_parameters": {},
- },
- "channel": "channel_value",
- }
- ],
- "webhook": "webhook_value",
- "return_partial_responses": True,
- "tag": "tag_value",
- "set_parameter_actions": [
- {
- "parameter": "parameter_value",
- "value": {
- "null_value": 0,
- "number_value": 0.1285,
- "string_value": "string_value_value",
- "bool_value": True,
- "struct_value": {},
- "list_value": {"values": {}},
- },
- }
- ],
- "conditional_cases": [
- {
- "cases": [
- {
- "condition": "condition_value",
- "case_content": [
- {"message": {}, "additional_cases": {}}
- ],
- }
- ]
- }
- ],
- "advanced_settings": {
- "audio_export_gcs_destination": {"uri": "uri_value"},
- "speech_settings": {
- "endpointer_sensitivity": 2402,
- "no_speech_timeout": {"seconds": 751, "nanos": 543},
- "use_timeout_based_endpointing": True,
- "models": {},
- },
- "dtmf_settings": {
- "enabled": True,
- "max_digits": 1065,
- "finish_digit": "finish_digit_value",
- "interdigit_timeout_duration": {},
- "endpointing_timeout_duration": {},
- },
- "logging_settings": {
- "enable_stackdriver_logging": True,
- "enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
- },
- },
- "enable_generative_fallback": True,
- },
- "target_page": "target_page_value",
- "target_flow": "target_flow_value",
- }
- ],
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = (
- gcdc_transition_route_group.CreateTransitionRouteGroupRequest.meta.fields[
- "transition_route_group"
- ]
- )
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init[
- "transition_route_group"
- ].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["transition_route_group"][field])):
- del request_init["transition_route_group"][field][i][subfield]
- else:
- del request_init["transition_route_group"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_transition_route_group.TransitionRouteGroup(
- name="name_value",
- display_name="display_name_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_transition_route_group(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_transition_route_group_rest_interceptors(null_interceptor):
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.TransitionRouteGroupsRestInterceptor(),
- )
- client = TransitionRouteGroupsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "post_create_transition_route_group",
- ) as post, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "pre_create_transition_route_group",
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_transition_route_group.CreateTransitionRouteGroupRequest.pb(
- gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_transition_route_group.TransitionRouteGroup.to_json(
- gcdc_transition_route_group.TransitionRouteGroup()
- )
- req.return_value.content = return_value
-
- request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_transition_route_group.TransitionRouteGroup()
-
- client.create_transition_route_group(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_transition_route_group_rest_bad_request(
- request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "transition_route_group": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_transition_route_group(request)
+def test_create_transition_route_group_rest_error():
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
@@ -5233,9 +4676,10 @@ def test_update_transition_route_group_rest_bad_request(
dict,
],
)
-def test_update_transition_route_group_rest_call_success(request_type):
+def test_update_transition_route_group_rest(request_type):
client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
# send a request that will satisfy transcoding
@@ -5340,7 +4784,6 @@ def test_update_transition_route_group_rest_call_success(request_type):
"logging_settings": {
"enable_stackdriver_logging": True,
"enable_interaction_logging": True,
- "enable_consent_based_redaction": True,
},
},
"enable_generative_fallback": True,
@@ -5434,13 +4877,13 @@ def get_message_fields(field):
)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
-
# Convert return value to protobuf type
return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.update_transition_route_group(request)
@@ -5450,6 +4893,145 @@ def get_message_fields(field):
assert response.display_name == "display_name_value"
+def test_update_transition_route_group_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_transition_route_group
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_transition_route_group
+ ] = mock_rpc
+
+ request = {}
+ client.update_transition_route_group(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_transition_route_group(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_update_transition_route_group_rest_required_fields(
+ request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest,
+):
+ transport_class = transports.TransitionRouteGroupsRestTransport
+
+ request_init = {}
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_transition_route_group._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).update_transition_route_group._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "language_code",
+ "update_mask",
+ )
+ )
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_transition_route_group.TransitionRouteGroup()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "patch",
+ "query_params": pb_request,
+ }
+ transcode_result["body"] = pb_request
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.update_transition_route_group(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
+
+
+def test_update_transition_route_group_rest_unset_required_fields():
+ transport = transports.TransitionRouteGroupsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
+ )
+
+ unset_fields = transport.update_transition_route_group._get_unset_required_fields(
+ {}
+ )
+ assert set(unset_fields) == (
+ set(
+ (
+ "languageCode",
+ "updateMask",
+ )
+ )
+ & set(("transitionRouteGroup",))
+ )
+
+
@pytest.mark.parametrize("null_interceptor", [True, False])
def test_update_transition_route_group_rest_interceptors(null_interceptor):
transport = transports.TransitionRouteGroupsRestTransport(
@@ -5459,7 +5041,6 @@ def test_update_transition_route_group_rest_interceptors(null_interceptor):
else transports.TransitionRouteGroupsRestInterceptor(),
)
client = TransitionRouteGroupsClient(transport=transport)
-
with mock.patch.object(
type(client.transport._session), "request"
) as req, mock.patch.object(
@@ -5483,12 +5064,14 @@ def test_update_transition_route_group_rest_interceptors(null_interceptor):
"query_params": pb_message,
}
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = gcdc_transition_route_group.TransitionRouteGroup.to_json(
- gcdc_transition_route_group.TransitionRouteGroup()
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = (
+ gcdc_transition_route_group.TransitionRouteGroup.to_json(
+ gcdc_transition_route_group.TransitionRouteGroup()
+ )
)
- req.return_value.content = return_value
request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
metadata = [
@@ -5510,15 +5093,20 @@ def test_update_transition_route_group_rest_interceptors(null_interceptor):
post.assert_called_once()
-def test_delete_transition_route_group_rest_bad_request(
- request_type=transition_route_group.DeleteTransitionRouteGroupRequest,
+def test_update_transition_route_group_rest_bad_request(
+ transport: str = "rest",
+ request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
+
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ "transition_route_group": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
}
request = request_type(**request_init)
@@ -5527,509 +5115,492 @@ def test_delete_transition_route_group_rest_bad_request(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
+ response_value = Response()
response_value.status_code = 400
- response_value.request = mock.Mock()
+ response_value.request = Request()
req.return_value = response_value
- client.delete_transition_route_group(request)
+ client.update_transition_route_group(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- transition_route_group.DeleteTransitionRouteGroupRequest,
- dict,
- ],
-)
-def test_delete_transition_route_group_rest_call_success(request_type):
+def test_update_transition_route_group_rest_flattened():
client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
- }
- request = request_type(**request_init)
-
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_transition_route_group(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
+ return_value = gcdc_transition_route_group.TransitionRouteGroup()
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_transition_route_group_rest_interceptors(null_interceptor):
- transport = transports.TransitionRouteGroupsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.TransitionRouteGroupsRestInterceptor(),
- )
- client = TransitionRouteGroupsClient(transport=transport)
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "transition_route_group": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
+ }
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.TransitionRouteGroupsRestInterceptor,
- "pre_delete_transition_route_group",
- ) as pre:
- pre.assert_not_called()
- pb_message = transition_route_group.DeleteTransitionRouteGroupRequest.pb(
- transition_route_group.DeleteTransitionRouteGroupRequest()
+ # get truthy value for each flattened field
+ mock_args = dict(
+ transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
+ name="name_value"
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
+ mock_args.update(sample_request)
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_transition_route_group.TransitionRouteGroup.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- request = transition_route_group.DeleteTransitionRouteGroupRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
+ client.update_transition_route_group(**mock_args)
- client.delete_transition_route_group(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{transition_route_group.name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}"
+ % client.transport._host,
+ args[1],
)
- pre.assert_called_once()
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
+def test_update_transition_route_group_rest_flattened_error(transport: str = "rest"):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ transport=transport,
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_transition_route_group(
+ gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(),
+ transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(
+ name="name_value"
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_update_transition_route_group_rest_error():
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
@pytest.mark.parametrize(
"request_type",
[
- locations_pb2.GetLocationRequest,
+ transition_route_group.DeleteTransitionRouteGroupRequest,
dict,
],
)
-def test_get_location_rest(request_type):
+def test_delete_transition_route_group_rest(request_type):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
request = request_type(**request_init)
+
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ return_value = None
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ json_return_value = ""
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
-
- response = client.get_location(request)
+ response = client.delete_transition_route_group(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+ assert response is None
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
+def test_delete_transition_route_group_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.delete_transition_route_group
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.delete_transition_route_group
+ ] = mock_rpc
+
+ request = {}
+ client.delete_transition_route_group(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_transition_route_group(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_delete_transition_route_group_rest_required_fields(
+ request_type=transition_route_group.DeleteTransitionRouteGroupRequest,
):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport_class = transports.TransitionRouteGroupsRestTransport
+
+ request_init = {}
+ request_init["name"] = ""
+ request = request_type(**request_init)
+ pb_request = request_type.pb(request)
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
+ # verify fields with default values are dropped
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_transition_route_group._get_unset_required_fields(jsonified_request)
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with default values are now present
+
+ jsonified_request["name"] = "name_value"
+
+ unset_fields = transport_class(
+ credentials=ga_credentials.AnonymousCredentials()
+ ).delete_transition_route_group._get_unset_required_fields(jsonified_request)
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("force",))
+ jsonified_request.update(unset_fields)
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
-
- request_init = {"name": "projects/sample1"}
request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request_type.pb(request)
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "delete",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
- req.return_value = response_value
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- response = client.list_locations(request)
+ response = client.delete_transition_route_group(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert expected_params == actual_params
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+def test_delete_transition_route_group_rest_unset_required_fields():
+ transport = transports.TransitionRouteGroupsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
+ unset_fields = transport.delete_transition_route_group._get_unset_required_fields(
+ {}
+ )
+ assert set(unset_fields) == (set(("force",)) & set(("name",)))
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = TransitionRouteGroupsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_transition_route_group_rest_interceptors(null_interceptor):
+ transport = transports.TransitionRouteGroupsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None
+ if null_interceptor
+ else transports.TransitionRouteGroupsRestInterceptor(),
)
+ client = TransitionRouteGroupsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.TransitionRouteGroupsRestInterceptor,
+ "pre_delete_transition_route_group",
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = transition_route_group.DeleteTransitionRouteGroupRequest.pb(
+ transition_route_group.DeleteTransitionRouteGroupRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
- req.return_value = response_value
+ request = transition_route_group.DeleteTransitionRouteGroupRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
- response = client.cancel_operation(request)
+ client.delete_transition_route_group(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert response is None
+ pre.assert_called_once()
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
+def test_delete_transition_route_group_rest_bad_request(
+ transport: str = "rest",
+ request_type=transition_route_group.DeleteTransitionRouteGroupRequest,
):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
+ transport=transport,
)
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
+ request = request_type(**request_init)
+
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
core_exceptions.BadRequest
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.get_operation(request)
+ client.delete_transition_route_group(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
+def test_delete_transition_route_group_rest_flattened():
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ return_value = None
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/transitionRouteGroups/sample5"
+ }
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
# Wrap the value into a proper Response obj
response_value = Response()
+ response_value.status_code = 200
json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- client.list_operations(request)
+ client.delete_transition_route_group(**mock_args)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{name=projects/*/locations/*/agents/*/flows/*/transitionRouteGroups/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_transition_route_group_rest_flattened_error(transport: str = "rest"):
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_transition_route_group(
+ transition_route_group.DeleteTransitionRouteGroupRequest(),
+ name="name_value",
+ )
-def test_initialize_client_w_rest():
+def test_delete_transition_route_group_rest_error():
client = TransitionRouteGroupsClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- assert client is not None
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_transition_route_groups_empty_call_rest():
- client = TransitionRouteGroupsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.list_transition_route_groups), "__call__"
- ) as call:
- client.list_transition_route_groups(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.ListTransitionRouteGroupsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_transition_route_group_empty_call_rest():
- client = TransitionRouteGroupsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = TransitionRouteGroupsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.get_transition_route_group), "__call__"
- ) as call:
- client.get_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.GetTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_transition_route_group_empty_call_rest():
- client = TransitionRouteGroupsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = TransitionRouteGroupsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.create_transition_route_group), "__call__"
- ) as call:
- client.create_transition_route_group(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.CreateTransitionRouteGroupRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = TransitionRouteGroupsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_transition_route_group_empty_call_rest():
- client = TransitionRouteGroupsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = TransitionRouteGroupsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_transition_route_group), "__call__"
- ) as call:
- client.update_transition_route_group(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest()
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = TransitionRouteGroupsClient(transport=transport)
+ assert client.transport is transport
- assert args[0] == request_msg
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.TransitionRouteGroupsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_transition_route_group_empty_call_rest():
- client = TransitionRouteGroupsClient(
+ transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_transition_route_group), "__call__"
- ) as call:
- client.delete_transition_route_group(request=None)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = transition_route_group.DeleteTransitionRouteGroupRequest()
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TransitionRouteGroupsGrpcTransport,
+ transports.TransitionRouteGroupsGrpcAsyncIOTransport,
+ transports.TransitionRouteGroupsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = TransitionRouteGroupsClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -6698,110 +6269,410 @@ def test_parse_common_billing_account_path():
assert expected == actual
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = TransitionRouteGroupsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = TransitionRouteGroupsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TransitionRouteGroupsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = TransitionRouteGroupsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nautilus",
+ }
+ path = TransitionRouteGroupsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TransitionRouteGroupsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "scallop"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = TransitionRouteGroupsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "abalone",
+ }
+ path = TransitionRouteGroupsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TransitionRouteGroupsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = TransitionRouteGroupsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = TransitionRouteGroupsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = TransitionRouteGroupsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = TransitionRouteGroupsClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = TransitionRouteGroupsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = TransitionRouteGroupsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = TransitionRouteGroupsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = TransitionRouteGroupsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = TransitionRouteGroupsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = TransitionRouteGroupsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = TransitionRouteGroupsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = TransitionRouteGroupsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = TransitionRouteGroupsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = TransitionRouteGroupsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = TransitionRouteGroupsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = TransitionRouteGroupsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = TransitionRouteGroupsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6831,7 +6702,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6884,7 +6755,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6929,7 +6800,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6970,7 +6841,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7025,7 +6896,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7072,7 +6943,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -7115,7 +6986,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7170,7 +7041,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7217,7 +7088,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -7260,7 +7131,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7315,7 +7186,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7362,7 +7233,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7405,7 +7276,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7459,7 +7330,9 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = TransitionRouteGroupsAsyncClient(credentials=async_anonymous_credentials())
+ client = TransitionRouteGroupsAsyncClient(
+ credentials=ga_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.
@@ -7505,7 +7378,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -7521,41 +7394,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = TransitionRouteGroupsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = TransitionRouteGroupsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = TransitionRouteGroupsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py
index 9b25e327f42c..45cfa7606fb5 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py
@@ -22,27 +22,10 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import (
future,
gapic_v1,
@@ -52,10 +35,9 @@
operations_v1,
path_template,
)
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import operation_async # type: ignore
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -64,8 +46,16 @@
from google.oauth2 import service_account
from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.versions import (
VersionsAsyncClient,
@@ -78,24 +68,10 @@
from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1140,6 +1116,25 @@ def test_list_versions(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+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=ga_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:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.ListVersionsRequest()
+
+
def test_list_versions_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1205,6 +1200,29 @@ def test_list_versions_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_versions_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # 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(
+ version.ListVersionsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.ListVersionsRequest()
+
+
@pytest.mark.asyncio
async def test_list_versions_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1213,7 +1231,7 @@ async def test_list_versions_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1228,23 +1246,27 @@ async def test_list_versions_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_versions
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_versions(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_versions(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1252,7 +1274,7 @@ async def test_list_versions_async(
transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1318,7 +1340,7 @@ def test_list_versions_field_headers():
@pytest.mark.asyncio
async def test_list_versions_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1388,7 +1410,7 @@ def test_list_versions_flattened_error():
@pytest.mark.asyncio
async def test_list_versions_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1417,7 +1439,7 @@ async def test_list_versions_flattened_async():
@pytest.mark.asyncio
async def test_list_versions_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1467,16 +1489,12 @@ def test_list_versions_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_versions(request={}, retry=retry, timeout=timeout)
+ pager = client.list_versions(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1527,7 +1545,7 @@ def test_list_versions_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_versions_async_pager():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1577,7 +1595,7 @@ async def test_list_versions_async_pager():
@pytest.mark.asyncio
async def test_list_versions_async_pages():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1665,6 +1683,25 @@ def test_get_version(request_type, transport: str = "grpc"):
assert response.state == version.Version.State.RUNNING
+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=ga_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:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.GetVersionRequest()
+
+
def test_get_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1728,6 +1765,32 @@ def test_get_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # 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",
+ display_name="display_name_value",
+ description="description_value",
+ state=version.Version.State.RUNNING,
+ )
+ )
+ response = await client.get_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.GetVersionRequest()
+
+
@pytest.mark.asyncio
async def test_get_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1736,7 +1799,7 @@ async def test_get_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1751,23 +1814,27 @@ async def test_get_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1775,7 +1842,7 @@ async def test_get_version_async(
transport: str = "grpc_asyncio", request_type=version.GetVersionRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1847,7 +1914,7 @@ def test_get_version_field_headers():
@pytest.mark.asyncio
async def test_get_version_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1915,7 +1982,7 @@ def test_get_version_flattened_error():
@pytest.mark.asyncio
async def test_get_version_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1942,7 +2009,7 @@ async def test_get_version_flattened_async():
@pytest.mark.asyncio
async def test_get_version_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1987,6 +2054,25 @@ def test_create_version(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+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=ga_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:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_version.CreateVersionRequest()
+
+
def test_create_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2043,9 +2129,8 @@ def test_create_version_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.create_version(request)
@@ -2055,6 +2140,27 @@ def test_create_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # 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()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_version.CreateVersionRequest()
+
+
@pytest.mark.asyncio
async def test_create_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2063,7 +2169,7 @@ async def test_create_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2078,28 +2184,31 @@ async def test_create_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.create_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2107,7 +2216,7 @@ async def test_create_version_async(
transport: str = "grpc_asyncio", request_type=gcdc_version.CreateVersionRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2170,7 +2279,7 @@ def test_create_version_field_headers():
@pytest.mark.asyncio
async def test_create_version_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2245,7 +2354,7 @@ def test_create_version_flattened_error():
@pytest.mark.asyncio
async def test_create_version_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2278,7 +2387,7 @@ async def test_create_version_flattened_async():
@pytest.mark.asyncio
async def test_create_version_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2333,6 +2442,25 @@ def test_update_version(request_type, transport: str = "grpc"):
assert response.state == gcdc_version.Version.State.RUNNING
+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=ga_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:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_version.UpdateVersionRequest()
+
+
def test_update_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2392,6 +2520,32 @@ def test_update_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # 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(
+ gcdc_version.Version(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_version.Version.State.RUNNING,
+ )
+ )
+ response = await client.update_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_version.UpdateVersionRequest()
+
+
@pytest.mark.asyncio
async def test_update_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2400,7 +2554,7 @@ async def test_update_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2415,23 +2569,27 @@ async def test_update_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2439,7 +2597,7 @@ async def test_update_version_async(
transport: str = "grpc_asyncio", request_type=gcdc_version.UpdateVersionRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2511,7 +2669,7 @@ def test_update_version_field_headers():
@pytest.mark.asyncio
async def test_update_version_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2586,7 +2744,7 @@ def test_update_version_flattened_error():
@pytest.mark.asyncio
async def test_update_version_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2619,7 +2777,7 @@ async def test_update_version_flattened_async():
@pytest.mark.asyncio
async def test_update_version_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2665,6 +2823,25 @@ def test_delete_version(request_type, transport: str = "grpc"):
assert response is None
+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=ga_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:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.DeleteVersionRequest()
+
+
def test_delete_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2728,6 +2905,25 @@ def test_delete_version_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # 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(None)
+ response = await client.delete_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.DeleteVersionRequest()
+
+
@pytest.mark.asyncio
async def test_delete_version_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2736,7 +2932,7 @@ async def test_delete_version_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2751,23 +2947,27 @@ async def test_delete_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2775,7 +2975,7 @@ async def test_delete_version_async(
transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2836,7 +3036,7 @@ def test_delete_version_field_headers():
@pytest.mark.asyncio
async def test_delete_version_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2904,7 +3104,7 @@ def test_delete_version_flattened_error():
@pytest.mark.asyncio
async def test_delete_version_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2931,7 +3131,7 @@ async def test_delete_version_flattened_async():
@pytest.mark.asyncio
async def test_delete_version_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2976,6 +3176,25 @@ def test_load_version(request_type, transport: str = "grpc"):
assert isinstance(response, future.Future)
+def test_load_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=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.load_version), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.load_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.LoadVersionRequest()
+
+
def test_load_version_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3032,9 +3251,8 @@ def test_load_version_use_cached_wrapped_rpc():
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
client.load_version(request)
@@ -3045,14 +3263,35 @@ def test_load_version_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_load_version_async_use_cached_wrapped_rpc(
- transport: str = "grpc_asyncio",
+async def test_load_version_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.load_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.load_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.LoadVersionRequest()
+
+
+@pytest.mark.asyncio
+async def test_load_version_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3067,28 +3306,31 @@ async def test_load_version_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.load_version
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.load_version(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
- # Operation methods call wrapper_fn to build a cached
- # client._transport.operations_client instance on first rpc call.
- # Subsequent calls should use the cached wrapper
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
wrapper_fn.reset_mock()
await client.load_version(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3096,7 +3338,7 @@ async def test_load_version_async(
transport: str = "grpc_asyncio", request_type=version.LoadVersionRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3159,7 +3401,7 @@ def test_load_version_field_headers():
@pytest.mark.asyncio
async def test_load_version_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3229,7 +3471,7 @@ def test_load_version_flattened_error():
@pytest.mark.asyncio
async def test_load_version_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3258,7 +3500,7 @@ async def test_load_version_flattened_async():
@pytest.mark.asyncio
async def test_load_version_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3308,6 +3550,25 @@ def test_compare_versions(request_type, transport: str = "grpc"):
assert response.target_version_content_json == "target_version_content_json_value"
+def test_compare_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=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.compare_versions), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.compare_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.CompareVersionsRequest()
+
+
def test_compare_versions_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -3377,6 +3638,30 @@ def test_compare_versions_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_compare_versions_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.compare_versions), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ version.CompareVersionsResponse(
+ base_version_content_json="base_version_content_json_value",
+ target_version_content_json="target_version_content_json_value",
+ )
+ )
+ response = await client.compare_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == version.CompareVersionsRequest()
+
+
@pytest.mark.asyncio
async def test_compare_versions_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -3385,7 +3670,7 @@ async def test_compare_versions_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3400,23 +3685,27 @@ async def test_compare_versions_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.compare_versions
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.compare_versions(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.compare_versions(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -3424,7 +3713,7 @@ async def test_compare_versions_async(
transport: str = "grpc_asyncio", request_type=version.CompareVersionsRequest
):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -3492,7 +3781,7 @@ def test_compare_versions_field_headers():
@pytest.mark.asyncio
async def test_compare_versions_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -3562,7 +3851,7 @@ def test_compare_versions_flattened_error():
@pytest.mark.asyncio
async def test_compare_versions_flattened_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -3591,7 +3880,7 @@ async def test_compare_versions_flattened_async():
@pytest.mark.asyncio
async def test_compare_versions_flattened_error_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -3603,6 +3892,48 @@ async def test_compare_versions_flattened_error_async():
)
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ version.ListVersionsRequest,
+ dict,
+ ],
+)
+def test_list_versions_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = version.ListVersionsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = version.ListVersionsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_versions(request)
+
+ # 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_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3735,6 +4066,85 @@ def test_list_versions_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_versions_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
+ )
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.VersionsRestInterceptor, "post_list_versions"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_list_versions"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = version.ListVersionsRequest.pb(version.ListVersionsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = version.ListVersionsResponse.to_json(
+ version.ListVersionsResponse()
+ )
+
+ request = version.ListVersionsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = version.ListVersionsResponse()
+
+ client.list_versions(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_versions_rest_bad_request(
+ transport: str = "rest", request_type=version.ListVersionsRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_versions(request)
+
+
def test_list_versions_rest_flattened():
client = VersionsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3857,6 +4267,54 @@ def test_list_versions_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ version.GetVersionRequest,
+ dict,
+ ],
+)
+def test_get_version_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = version.Version(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=version.Version.State.RUNNING,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = version.Version.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, version.Version)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == version.Version.State.RUNNING
+
+
def test_get_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3974,28 +4432,105 @@ def test_get_version_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_get_version_rest_flattened():
- client = VersionsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_version_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
)
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.VersionsRestInterceptor, "post_get_version"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_get_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = version.GetVersionRequest.pb(version.GetVersionRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = version.Version.to_json(version.Version())
+
+ request = version.GetVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = version.Version()
+
+ client.get_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_version_rest_bad_request(
+ transport: str = "rest", request_type=version.GetVersionRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_version(request)
+
+
+def test_get_version_rest_flattened():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = version.Version()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
+ )
+ mock_args.update(sample_request)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = version.Version()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
# Wrap the value into a proper Response obj
response_value = Response()
response_value.status_code = 200
@@ -4033,6 +4568,128 @@ def test_get_version_rest_flattened_error(transport: str = "rest"):
)
+def test_get_version_rest_error():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_version.CreateVersionRequest,
+ dict,
+ ],
+)
+def test_create_version_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request_init["version"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "nlu_settings": {
+ "model_type": 1,
+ "classification_threshold": 0.25520000000000004,
+ "model_training_mode": 1,
+ },
+ "create_time": {"seconds": 751, "nanos": 543},
+ "state": 1,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_version.CreateVersionRequest.meta.fields["version"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["version"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["version"][field])):
+ del request_init["version"][field][i][subfield]
+ else:
+ del request_init["version"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
def test_create_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4162,34 +4819,117 @@ def test_create_version_rest_unset_required_fields():
)
-def test_create_version_rest_flattened():
- client = VersionsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_version_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.VersionsRestInterceptor, "post_create_version"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_create_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_version.CreateVersionRequest.pb(
+ gcdc_version.CreateVersionRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- version=gcdc_version.Version(name="name_value"),
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
)
- mock_args.update(sample_request)
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
+ request = gcdc_version.CreateVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
+
+ client.create_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_version_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_version.CreateVersionRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_version(request)
+
+
+def test_create_version_rest_flattened():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ version=gcdc_version.Version(name="name_value"),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
client.create_version(**mock_args)
@@ -4221,6 +4961,141 @@ def test_create_version_rest_flattened_error(transport: str = "rest"):
)
+def test_create_version_rest_error():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_version.UpdateVersionRequest,
+ dict,
+ ],
+)
+def test_update_version_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "version": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ }
+ request_init["version"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "nlu_settings": {
+ "model_type": 1,
+ "classification_threshold": 0.25520000000000004,
+ "model_training_mode": 1,
+ },
+ "create_time": {"seconds": 751, "nanos": 543},
+ "state": 1,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_version.UpdateVersionRequest.meta.fields["version"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["version"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["version"][field])):
+ del request_init["version"][field][i][subfield]
+ else:
+ del request_init["version"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_version.Version(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ state=gcdc_version.Version.State.RUNNING,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_version.Version.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_version.Version)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert response.state == gcdc_version.Version.State.RUNNING
+
+
def test_update_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4346,36 +5221,117 @@ def test_update_version_rest_unset_required_fields():
)
-def test_update_version_rest_flattened():
- client = VersionsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_version_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_version.Version()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "version": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.VersionsRestInterceptor, "post_update_version"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_update_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_version.UpdateVersionRequest.pb(
+ gcdc_version.UpdateVersionRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
}
- # get truthy value for each flattened field
- mock_args = dict(
- version=gcdc_version.Version(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_version.Version.to_json(gcdc_version.Version())
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcdc_version.Version.pb(return_value)
+ request = gcdc_version.UpdateVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_version.Version()
+
+ client.update_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_version_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_version.UpdateVersionRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "version": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_version(request)
+
+
+def test_update_version_rest_flattened():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_version.Version()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "version": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ version=gcdc_version.Version(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+ mock_args.update(sample_request)
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_version.Version.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
@@ -4409,6 +5365,49 @@ def test_update_version_rest_flattened_error(transport: str = "rest"):
)
+def test_update_version_rest_error():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ version.DeleteVersionRequest,
+ dict,
+ ],
+)
+def test_delete_version_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
def test_delete_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4523,6 +5522,77 @@ def test_delete_version_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_version_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
+ )
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_delete_version"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = version.DeleteVersionRequest.pb(version.DeleteVersionRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = version.DeleteVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_version_rest_bad_request(
+ transport: str = "rest", request_type=version.DeleteVersionRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_version(request)
+
+
def test_delete_version_rest_flattened():
client = VersionsClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4580,6 +5650,49 @@ def test_delete_version_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_version_rest_error():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ version.LoadVersionRequest,
+ dict,
+ ],
+)
+def test_load_version_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation(name="operations/spam")
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.load_version(request)
+
+ # Establish that the response is the type that we expect.
+ assert response.operation.name == "operations/spam"
+
+
def test_load_version_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4699,15 +5812,96 @@ def test_load_version_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
-def test_load_version_rest_flattened():
- client = VersionsClient(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_load_version_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
)
+ client = VersionsClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ operation.Operation, "_set_result_from_operation"
+ ), mock.patch.object(
+ transports.VersionsRestInterceptor, "post_load_version"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_load_version"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = version.LoadVersionRequest.pb(version.LoadVersionRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = json_format.MessageToJson(
+ operations_pb2.Operation()
+ )
+
+ request = version.LoadVersionRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = operations_pb2.Operation()
+
+ client.load_version(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_load_version_rest_bad_request(
+ transport: str = "rest", request_type=version.LoadVersionRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.load_version(request)
+
+
+def test_load_version_rest_flattened():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
return_value = operations_pb2.Operation(name="operations/spam")
# get arguments that satisfy an http rule for this method
@@ -4756,6 +5950,56 @@ def test_load_version_rest_flattened_error(transport: str = "rest"):
)
+def test_load_version_rest_error():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ version.CompareVersionsRequest,
+ dict,
+ ],
+)
+def test_compare_versions_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = version.CompareVersionsResponse(
+ base_version_content_json="base_version_content_json_value",
+ target_version_content_json="target_version_content_json_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = version.CompareVersionsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.compare_versions(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, version.CompareVersionsResponse)
+ assert response.base_version_content_json == "base_version_content_json_value"
+ assert response.target_version_content_json == "target_version_content_json_value"
+
+
def test_compare_versions_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -4890,1758 +6134,72 @@ def test_compare_versions_rest_unset_required_fields():
)
-def test_compare_versions_rest_flattened():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = version.CompareVersionsResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- base_version="base_version_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = version.CompareVersionsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.compare_versions(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v3beta1/{base_version=projects/*/locations/*/agents/*/flows/*/versions/*}:compareVersions"
- % client.transport._host,
- args[1],
- )
-
-
-def test_compare_versions_rest_flattened_error(transport: str = "rest"):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.compare_versions(
- version.CompareVersionsRequest(),
- base_version="base_version_value",
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.VersionsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.VersionsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = VersionsClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.VersionsGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = VersionsClient(
- client_options=options,
- transport=transport,
- )
-
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = VersionsClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.VersionsGrpcTransport(
- credentials=ga_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(
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_compare_versions_rest_interceptors(null_interceptor):
+ transport = transports.VersionsRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
)
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=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.VersionsRestInterceptor, "post_compare_versions"
+ ) as post, mock.patch.object(
+ transports.VersionsRestInterceptor, "pre_compare_versions"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = version.CompareVersionsRequest.pb(version.CompareVersionsRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- transport = transports.VersionsGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.VersionsGrpcTransport,
- transports.VersionsGrpcAsyncIOTransport,
- transports.VersionsRestTransport,
- ],
-)
-def test_transport_adc(transport_class):
- # Test default credentials are used if not provided.
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = VersionsClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_versions_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
- call.return_value = version.ListVersionsResponse()
- client.list_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.ListVersionsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_version_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, 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=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.GetVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_version_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, 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=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.CreateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_version_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_version), "__call__") as call:
- call.return_value = gcdc_version.Version()
- client.update_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.UpdateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_version_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_version), "__call__") as call:
- call.return_value = None
- client.delete_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.DeleteVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_load_version_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.load_version), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.load_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.LoadVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_compare_versions_empty_call_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.compare_versions), "__call__") as call:
- call.return_value = version.CompareVersionsResponse()
- client.compare_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.CompareVersionsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = VersionsAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_versions_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, 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(
- version.ListVersionsResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.ListVersionsRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_version_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, 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",
- display_name="display_name_value",
- description="description_value",
- state=version.Version.State.RUNNING,
- )
- )
- await client.get_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.GetVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_version_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, 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")
- )
- await client.create_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.CreateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_version_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, 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(
- gcdc_version.Version(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_version.Version.State.RUNNING,
- )
- )
- await client.update_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.UpdateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_version_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, 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(None)
- await client.delete_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.DeleteVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_load_version_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.load_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")
- )
- await client.load_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.LoadVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_compare_versions_empty_call_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.compare_versions), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- version.CompareVersionsResponse(
- base_version_content_json="base_version_content_json_value",
- target_version_content_json="target_version_content_json_value",
- )
- )
- await client.compare_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.CompareVersionsRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = VersionsClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_versions_rest_bad_request(request_type=version.ListVersionsRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_versions(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- version.ListVersionsRequest,
- dict,
- ],
-)
-def test_list_versions_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = version.ListVersionsResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = version.ListVersionsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_versions(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListVersionsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_versions_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.VersionsRestInterceptor, "post_list_versions"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_list_versions"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = version.ListVersionsRequest.pb(version.ListVersionsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = version.ListVersionsResponse.to_json(
- version.ListVersionsResponse()
- )
- req.return_value.content = return_value
-
- request = version.ListVersionsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = version.ListVersionsResponse()
-
- client.list_versions(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_version_rest_bad_request(request_type=version.GetVersionRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- version.GetVersionRequest,
- dict,
- ],
-)
-def test_get_version_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = version.Version(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=version.Version.State.RUNNING,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = version.Version.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_version(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, version.Version)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == version.Version.State.RUNNING
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_version_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.VersionsRestInterceptor, "post_get_version"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_get_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = version.GetVersionRequest.pb(version.GetVersionRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = version.Version.to_json(version.Version())
- req.return_value.content = return_value
-
- request = version.GetVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = version.Version()
-
- client.get_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_version_rest_bad_request(
- request_type=gcdc_version.CreateVersionRequest,
-):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_version.CreateVersionRequest,
- dict,
- ],
-)
-def test_create_version_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "parent": "projects/sample1/locations/sample2/agents/sample3/flows/sample4"
- }
- request_init["version"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "description": "description_value",
- "nlu_settings": {
- "model_type": 1,
- "classification_threshold": 0.25520000000000004,
- "model_training_mode": 1,
- },
- "create_time": {"seconds": 751, "nanos": 543},
- "state": 1,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_version.CreateVersionRequest.meta.fields["version"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["version"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["version"][field])):
- del request_init["version"][field][i][subfield]
- else:
- del request_init["version"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_version(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_version_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.VersionsRestInterceptor, "post_create_version"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_create_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_version.CreateVersionRequest.pb(
- gcdc_version.CreateVersionRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = gcdc_version.CreateVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.create_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_version_rest_bad_request(
- request_type=gcdc_version.UpdateVersionRequest,
-):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "version": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_version.UpdateVersionRequest,
- dict,
- ],
-)
-def test_update_version_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "version": {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- }
- request_init["version"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5",
- "display_name": "display_name_value",
- "description": "description_value",
- "nlu_settings": {
- "model_type": 1,
- "classification_threshold": 0.25520000000000004,
- "model_training_mode": 1,
- },
- "create_time": {"seconds": 751, "nanos": 543},
- "state": 1,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_version.UpdateVersionRequest.meta.fields["version"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["version"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["version"][field])):
- del request_init["version"][field][i][subfield]
- else:
- del request_init["version"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_version.Version(
- name="name_value",
- display_name="display_name_value",
- description="description_value",
- state=gcdc_version.Version.State.RUNNING,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_version.Version.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_version(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_version.Version)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.description == "description_value"
- assert response.state == gcdc_version.Version.State.RUNNING
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_version_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.VersionsRestInterceptor, "post_update_version"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_update_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_version.UpdateVersionRequest.pb(
- gcdc_version.UpdateVersionRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_version.Version.to_json(gcdc_version.Version())
- req.return_value.content = return_value
-
- request = gcdc_version.UpdateVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_version.Version()
-
- client.update_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_version_rest_bad_request(request_type=version.DeleteVersionRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- version.DeleteVersionRequest,
- dict,
- ],
-)
-def test_delete_version_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_version(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_version_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_delete_version"
- ) as pre:
- pre.assert_not_called()
- pb_message = version.DeleteVersionRequest.pb(version.DeleteVersionRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = version.DeleteVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_load_version_rest_bad_request(request_type=version.LoadVersionRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.load_version(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- version.LoadVersionRequest,
- dict,
- ],
-)
-def test_load_version_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.load_version(request)
-
- # Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_load_version_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- operation.Operation, "_set_result_from_operation"
- ), mock.patch.object(
- transports.VersionsRestInterceptor, "post_load_version"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_load_version"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = version.LoadVersionRequest.pb(version.LoadVersionRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = json_format.MessageToJson(operations_pb2.Operation())
- req.return_value.content = return_value
-
- request = version.LoadVersionRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.load_version(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_compare_versions_rest_bad_request(request_type=version.CompareVersionsRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.compare_versions(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- version.CompareVersionsRequest,
- dict,
- ],
-)
-def test_compare_versions_rest_call_success(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = version.CompareVersionsResponse(
- base_version_content_json="base_version_content_json_value",
- target_version_content_json="target_version_content_json_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = version.CompareVersionsResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.compare_versions(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, version.CompareVersionsResponse)
- assert response.base_version_content_json == "base_version_content_json_value"
- assert response.target_version_content_json == "target_version_content_json_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_compare_versions_rest_interceptors(null_interceptor):
- transport = transports.VersionsRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.VersionsRestInterceptor(),
- )
- client = VersionsClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.VersionsRestInterceptor, "post_compare_versions"
- ) as post, mock.patch.object(
- transports.VersionsRestInterceptor, "pre_compare_versions"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = version.CompareVersionsRequest.pb(version.CompareVersionsRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
+ req.return_value = Response()
req.return_value.status_code = 200
- return_value = version.CompareVersionsResponse.to_json(
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = version.CompareVersionsResponse.to_json(
version.CompareVersionsResponse()
- )
- req.return_value.content = return_value
-
- request = version.CompareVersionsRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = version.CompareVersionsResponse()
-
- client.compare_versions(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
+ )
- req.return_value = response_value
+ request = version.CompareVersionsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = version.CompareVersionsResponse()
- response = client.get_operation(request)
+ client.compare_versions(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+ pre.assert_called_once()
+ post.assert_called_once()
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
+def test_compare_versions_rest_bad_request(
+ transport: str = "rest", request_type=version.CompareVersionsRequest
):
client = VersionsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+ request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
with mock.patch.object(Session, "request") as req, pytest.raises(
@@ -6649,210 +6207,181 @@ def test_list_operations_rest_bad_request(
):
# Wrap the value into a proper Response obj
response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
response_value.status_code = 400
response_value.request = Request()
req.return_value = response_value
- client.list_operations(request)
+ client.compare_versions(request)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
+def test_compare_versions_rest_flattened():
client = VersionsClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
)
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
# Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
+ with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
+ return_value = version.CompareVersionsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "base_version": "projects/sample1/locations/sample2/agents/sample3/flows/sample4/versions/sample5"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ base_version="base_version_value",
+ )
+ mock_args.update(sample_request)
# Wrap the value into a proper Response obj
- response_value = mock.Mock()
+ response_value = Response()
response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = version.CompareVersionsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
+ response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
+ client.compare_versions(**mock_args)
-def test_initialize_client_w_rest():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v3beta1/{base_version=projects/*/locations/*/agents/*/flows/*/versions/*}:compareVersions"
+ % client.transport._host,
+ args[1],
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_versions_empty_call_rest():
+def test_compare_versions_rest_flattened_error(transport: str = "rest"):
client = VersionsClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
- client.list_versions(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.ListVersionsRequest()
-
- assert args[0] == request_msg
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.compare_versions(
+ version.CompareVersionsRequest(),
+ base_version="base_version_value",
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_version_empty_call_rest():
+def test_compare_versions_rest_error():
client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_version), "__call__") as call:
- client.get_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.GetVersionRequest()
-
- assert args[0] == request_msg
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_version_empty_call_rest():
- client = VersionsClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.VersionsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_version), "__call__") as call:
- client.create_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.CreateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_version_empty_call_rest():
- client = VersionsClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.VersionsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_version), "__call__") as call:
- client.update_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_version.UpdateVersionRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_version_empty_call_rest():
- client = VersionsClient(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.VersionsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options=options,
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_version), "__call__") as call:
- client.delete_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.DeleteVersionRequest()
-
- assert args[0] == request_msg
-
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_load_version_empty_call_rest():
- client = VersionsClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.VersionsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.load_version), "__call__") as call:
- client.load_version(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.LoadVersionRequest()
- assert args[0] == request_msg
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = VersionsClient(transport=transport)
+ assert client.transport is transport
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_compare_versions_empty_call_rest():
- client = VersionsClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.VersionsGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
+ channel = transport.grpc_channel
+ assert channel
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.compare_versions), "__call__") as call:
- client.compare_versions(request=None)
+ transport = transports.VersionsGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = version.CompareVersionsRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.VersionsGrpcTransport,
+ transports.VersionsGrpcAsyncIOTransport,
+ transports.VersionsRestTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
-def test_versions_rest_lro_client():
- client = VersionsClient(
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = VersionsClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- transport = client.transport
-
- # Ensure that we have an api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.AbstractOperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -7098,15 +6627,32 @@ def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class):
)
-def test_versions_http_transport_client_cert_source_for_mtls():
- cred = ga_credentials.AnonymousCredentials()
- with mock.patch(
- "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
- ) as mock_configure_mtls_channel:
- transports.VersionsRestTransport(
- credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
- )
- mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+def test_versions_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.VersionsRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+def test_versions_rest_lro_client():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
@pytest.mark.parametrize(
@@ -7394,115 +6940,415 @@ def test_parse_common_billing_account_path():
}
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
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "squid"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = VersionsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "clam",
+ }
+ 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 = "whelk"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = VersionsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "octopus",
+ }
+ 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 = "oyster"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = VersionsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nudibranch",
+ }
+ 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 = "cuttlefish"
+ location = "mussel"
+ 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": "winkle",
+ "location": "nautilus",
+ }
+ 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_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.VersionsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = VersionsClient(
+ credentials=ga_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=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = VersionsAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "squid"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = VersionsClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "clam",
- }
- path = VersionsClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = VersionsClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "whelk"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = VersionsClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "octopus",
- }
- path = VersionsClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = VersionsClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "oyster"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = VersionsClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "nudibranch",
- }
- path = VersionsClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = VersionsClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "cuttlefish"
- location = "mussel"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = VersionsClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "winkle",
- "location": "nautilus",
- }
- path = VersionsClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = VersionsClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.VersionsTransport, "_prep_wrapped_messages"
- ) as prep:
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.VersionsTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = VersionsClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -7532,7 +7378,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7585,7 +7431,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7630,7 +7476,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -7671,7 +7517,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7726,7 +7572,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7773,7 +7619,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -7816,7 +7662,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -7871,7 +7717,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -7918,7 +7764,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -7961,7 +7807,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8016,7 +7862,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -8063,7 +7909,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8106,7 +7952,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -8158,7 +8004,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = VersionsAsyncClient(credentials=async_anonymous_credentials())
+ client = VersionsAsyncClient(credentials=ga_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.
@@ -8204,7 +8050,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -8220,41 +8066,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = VersionsAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = VersionsClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = VersionsClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py
index 4c76e6883594..ead955184063 100644
--- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py
+++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py
@@ -22,31 +22,13 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import AsyncIterable, Iterable
+from collections.abc import Iterable
import json
import math
-from google.api_core import api_core_version
-from google.protobuf import json_format
-import grpc
-from grpc.experimental import aio
-from proto.marshal.rules import wrappers
-from proto.marshal.rules.dates import DurationRule, TimestampRule
-import pytest
-from requests import PreparedRequest, Request, Response
-from requests.sessions import Session
-
-try:
- from google.auth.aio import credentials as ga_credentials_async
-
- HAS_GOOGLE_AUTH_AIO = True
-except ImportError: # pragma: NO COVER
- HAS_GOOGLE_AUTH_AIO = False
-
from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template
-from google.api_core import client_options
+from google.api_core import api_core_version, client_options
from google.api_core import exceptions as core_exceptions
-from google.api_core import retry as retries
import google.auth
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
@@ -55,6 +37,14 @@
from google.oauth2 import service_account
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import json_format
+import grpc
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+import pytest
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
from google.cloud.dialogflowcx_v3beta1.services.webhooks import (
WebhooksAsyncClient,
@@ -66,24 +56,10 @@
from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook
-async def mock_async_gen(data, chunk_size=1):
- for i in range(0, len(data)): # pragma: NO COVER
- chunk = data[i : i + chunk_size]
- yield chunk.encode("utf-8")
-
-
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
-# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
-# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
-def async_anonymous_credentials():
- if HAS_GOOGLE_AUTH_AIO:
- return ga_credentials_async.AnonymousCredentials()
- return ga_credentials.AnonymousCredentials()
-
-
# 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.
@@ -1128,6 +1104,25 @@ def test_list_webhooks(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
+def test_list_webhooks_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 = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_webhooks()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.ListWebhooksRequest()
+
+
def test_list_webhooks_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1193,6 +1188,29 @@ def test_list_webhooks_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_list_webhooks_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ webhook.ListWebhooksResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_webhooks()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.ListWebhooksRequest()
+
+
@pytest.mark.asyncio
async def test_list_webhooks_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1201,7 +1219,7 @@ async def test_list_webhooks_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1216,23 +1234,27 @@ async def test_list_webhooks_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.list_webhooks
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.list_webhooks(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.list_webhooks(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1240,7 +1262,7 @@ async def test_list_webhooks_async(
transport: str = "grpc_asyncio", request_type=webhook.ListWebhooksRequest
):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1306,7 +1328,7 @@ def test_list_webhooks_field_headers():
@pytest.mark.asyncio
async def test_list_webhooks_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1376,7 +1398,7 @@ def test_list_webhooks_flattened_error():
@pytest.mark.asyncio
async def test_list_webhooks_flattened_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1405,7 +1427,7 @@ async def test_list_webhooks_flattened_async():
@pytest.mark.asyncio
async def test_list_webhooks_flattened_error_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1455,16 +1477,12 @@ def test_list_webhooks_pager(transport_name: str = "grpc"):
)
expected_metadata = ()
- retry = retries.Retry()
- timeout = 5
expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_webhooks(request={}, retry=retry, timeout=timeout)
+ pager = client.list_webhooks(request={})
assert pager._metadata == expected_metadata
- assert pager._retry == retry
- assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1515,7 +1533,7 @@ def test_list_webhooks_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_webhooks_async_pager():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1565,7 +1583,7 @@ async def test_list_webhooks_async_pager():
@pytest.mark.asyncio
async def test_list_webhooks_async_pages():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1651,6 +1669,25 @@ def test_get_webhook(request_type, transport: str = "grpc"):
assert response.disabled is True
+def test_get_webhook_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 = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_webhook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.GetWebhookRequest()
+
+
def test_get_webhook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -1714,6 +1751,31 @@ def test_get_webhook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_get_webhook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_webhook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+ )
+ response = await client.get_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.GetWebhookRequest()
+
+
@pytest.mark.asyncio
async def test_get_webhook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -1722,7 +1784,7 @@ async def test_get_webhook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1737,23 +1799,27 @@ async def test_get_webhook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.get_webhook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.get_webhook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.get_webhook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -1761,7 +1827,7 @@ async def test_get_webhook_async(
transport: str = "grpc_asyncio", request_type=webhook.GetWebhookRequest
):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -1831,7 +1897,7 @@ def test_get_webhook_field_headers():
@pytest.mark.asyncio
async def test_get_webhook_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1899,7 +1965,7 @@ def test_get_webhook_flattened_error():
@pytest.mark.asyncio
async def test_get_webhook_flattened_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1926,7 +1992,7 @@ async def test_get_webhook_flattened_async():
@pytest.mark.asyncio
async def test_get_webhook_flattened_error_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1978,6 +2044,25 @@ def test_create_webhook(request_type, transport: str = "grpc"):
assert response.disabled is True
+def test_create_webhook_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 = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_webhook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_webhook.CreateWebhookRequest()
+
+
def test_create_webhook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2041,6 +2126,31 @@ def test_create_webhook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_create_webhook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_webhook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+ )
+ response = await client.create_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_webhook.CreateWebhookRequest()
+
+
@pytest.mark.asyncio
async def test_create_webhook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2049,7 +2159,7 @@ async def test_create_webhook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2064,23 +2174,27 @@ async def test_create_webhook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.create_webhook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.create_webhook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.create_webhook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2088,7 +2202,7 @@ async def test_create_webhook_async(
transport: str = "grpc_asyncio", request_type=gcdc_webhook.CreateWebhookRequest
):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2158,7 +2272,7 @@ def test_create_webhook_field_headers():
@pytest.mark.asyncio
async def test_create_webhook_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2233,7 +2347,7 @@ def test_create_webhook_flattened_error():
@pytest.mark.asyncio
async def test_create_webhook_flattened_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2266,7 +2380,7 @@ async def test_create_webhook_flattened_async():
@pytest.mark.asyncio
async def test_create_webhook_flattened_error_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2319,6 +2433,25 @@ def test_update_webhook(request_type, transport: str = "grpc"):
assert response.disabled is True
+def test_update_webhook_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 = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_webhook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_webhook.UpdateWebhookRequest()
+
+
def test_update_webhook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2378,6 +2511,31 @@ def test_update_webhook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_update_webhook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_webhook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcdc_webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+ )
+ response = await client.update_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == gcdc_webhook.UpdateWebhookRequest()
+
+
@pytest.mark.asyncio
async def test_update_webhook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2386,7 +2544,7 @@ async def test_update_webhook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2401,23 +2559,27 @@ async def test_update_webhook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.update_webhook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.update_webhook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.update_webhook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2425,7 +2587,7 @@ async def test_update_webhook_async(
transport: str = "grpc_asyncio", request_type=gcdc_webhook.UpdateWebhookRequest
):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2495,7 +2657,7 @@ def test_update_webhook_field_headers():
@pytest.mark.asyncio
async def test_update_webhook_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2570,7 +2732,7 @@ def test_update_webhook_flattened_error():
@pytest.mark.asyncio
async def test_update_webhook_flattened_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2603,7 +2765,7 @@ async def test_update_webhook_flattened_async():
@pytest.mark.asyncio
async def test_update_webhook_flattened_error_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2649,6 +2811,25 @@ def test_delete_webhook(request_type, transport: str = "grpc"):
assert response is None
+def test_delete_webhook_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 = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.DeleteWebhookRequest()
+
+
def test_delete_webhook_non_empty_request_with_auto_populated_field():
# This test is a coverage failsafe to make sure that UUID4 fields are
# automatically populated, according to AIP-4235, with non-empty requests.
@@ -2712,6 +2893,25 @@ def test_delete_webhook_use_cached_wrapped_rpc():
assert mock_rpc.call_count == 2
+@pytest.mark.asyncio
+async def test_delete_webhook_empty_call_async():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_webhook()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == webhook.DeleteWebhookRequest()
+
+
@pytest.mark.asyncio
async def test_delete_webhook_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
@@ -2720,7 +2920,7 @@ async def test_delete_webhook_async_use_cached_wrapped_rpc(
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2735,23 +2935,27 @@ async def test_delete_webhook_async_use_cached_wrapped_rpc(
)
# Replace cached wrapped function with mock
- mock_rpc = mock.AsyncMock()
- mock_rpc.return_value = mock.Mock()
+ class AwaitableMock(mock.AsyncMock):
+ def __await__(self):
+ self.await_count += 1
+ return iter([])
+
+ mock_object = AwaitableMock()
client._client._transport._wrapped_methods[
client._client._transport.delete_webhook
- ] = mock_rpc
+ ] = mock_object
request = {}
await client.delete_webhook(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+ assert mock_object.call_count == 1
await client.delete_webhook(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
- assert mock_rpc.call_count == 2
+ assert mock_object.call_count == 2
@pytest.mark.asyncio
@@ -2759,7 +2963,7 @@ async def test_delete_webhook_async(
transport: str = "grpc_asyncio", request_type=webhook.DeleteWebhookRequest
):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -2820,7 +3024,7 @@ def test_delete_webhook_field_headers():
@pytest.mark.asyncio
async def test_delete_webhook_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2888,7 +3092,7 @@ def test_delete_webhook_flattened_error():
@pytest.mark.asyncio
async def test_delete_webhook_flattened_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2915,7 +3119,7 @@ async def test_delete_webhook_flattened_async():
@pytest.mark.asyncio
async def test_delete_webhook_flattened_error_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2927,18 +3131,58 @@ async def test_delete_webhook_flattened_error_async():
)
-def test_list_webhooks_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ webhook.ListWebhooksRequest,
+ dict,
+ ],
+)
+def test_list_webhooks_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = webhook.ListWebhooksResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = webhook.ListWebhooksResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.list_webhooks(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListWebhooksPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_webhooks_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
# Ensure method has been cached
assert client._transport.list_webhooks in client._transport._wrapped_methods
@@ -3059,6 +3303,83 @@ def test_list_webhooks_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_webhooks_rest_interceptors(null_interceptor):
+ transport = transports.WebhooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
+ )
+ client = WebhooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.WebhooksRestInterceptor, "post_list_webhooks"
+ ) as post, mock.patch.object(
+ transports.WebhooksRestInterceptor, "pre_list_webhooks"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = webhook.ListWebhooksRequest.pb(webhook.ListWebhooksRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = webhook.ListWebhooksResponse.to_json(
+ webhook.ListWebhooksResponse()
+ )
+
+ request = webhook.ListWebhooksRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = webhook.ListWebhooksResponse()
+
+ client.list_webhooks(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_list_webhooks_rest_bad_request(
+ transport: str = "rest", request_type=webhook.ListWebhooksRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_webhooks(request)
+
+
def test_list_webhooks_rest_flattened():
client = WebhooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3177,6 +3498,52 @@ def test_list_webhooks_rest_pager(transport: str = "rest"):
assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ webhook.GetWebhookRequest,
+ dict,
+ ],
+)
+def test_get_webhook_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = webhook.Webhook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.get_webhook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, webhook.Webhook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.disabled is True
+
+
def test_get_webhook_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -3294,6 +3661,83 @@ def test_get_webhook_rest_unset_required_fields():
assert set(unset_fields) == (set(()) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_webhook_rest_interceptors(null_interceptor):
+ transport = transports.WebhooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
+ )
+ client = WebhooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.WebhooksRestInterceptor, "post_get_webhook"
+ ) as post, mock.patch.object(
+ transports.WebhooksRestInterceptor, "pre_get_webhook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = webhook.GetWebhookRequest.pb(webhook.GetWebhookRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = webhook.Webhook.to_json(webhook.Webhook())
+
+ request = webhook.GetWebhookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = webhook.Webhook()
+
+ client.get_webhook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_get_webhook_rest_bad_request(
+ transport: str = "rest", request_type=webhook.GetWebhookRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_webhook(request)
+
+
def test_get_webhook_rest_flattened():
client = WebhooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3353,26 +3797,168 @@ def test_get_webhook_rest_flattened_error(transport: str = "rest"):
)
-def test_create_webhook_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+def test_get_webhook_rest_error():
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
- # Ensure method has been cached
- assert client._transport.create_webhook in client._transport._wrapped_methods
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_webhook.CreateWebhookRequest,
+ dict,
+ ],
+)
+def test_create_webhook_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request_init["webhook"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "generic_web_service": {
+ "uri": "uri_value",
+ "username": "username_value",
+ "password": "password_value",
+ "request_headers": {},
+ "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"],
+ "oauth_config": {
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ "scopes": ["scopes_value1", "scopes_value2"],
+ },
+ "service_agent_auth": 1,
+ "webhook_type": 1,
+ "http_method": 1,
+ "request_body": "request_body_value",
+ "parameter_mapping": {},
+ },
+ "service_directory": {"service": "service_value", "generic_web_service": {}},
+ "timeout": {"seconds": 751, "nanos": 543},
+ "disabled": True,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_webhook.CreateWebhookRequest.meta.fields["webhook"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["webhook"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["webhook"][field])):
+ del request_init["webhook"][field][i][subfield]
+ else:
+ del request_init["webhook"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_webhook.Webhook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.create_webhook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_webhook.Webhook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.disabled is True
+
+
+def test_create_webhook_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_webhook in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[client._transport.create_webhook] = mock_rpc
@@ -3481,6 +4067,83 @@ def test_create_webhook_rest_unset_required_fields():
)
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_webhook_rest_interceptors(null_interceptor):
+ transport = transports.WebhooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
+ )
+ client = WebhooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.WebhooksRestInterceptor, "post_create_webhook"
+ ) as post, mock.patch.object(
+ transports.WebhooksRestInterceptor, "pre_create_webhook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_webhook.CreateWebhookRequest.pb(
+ gcdc_webhook.CreateWebhookRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_webhook.Webhook.to_json(gcdc_webhook.Webhook())
+
+ request = gcdc_webhook.CreateWebhookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_webhook.Webhook()
+
+ client.create_webhook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_create_webhook_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_webhook.CreateWebhookRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.create_webhook(request)
+
+
def test_create_webhook_rest_flattened():
client = WebhooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3540,34 +4203,180 @@ def test_create_webhook_rest_flattened_error(transport: str = "rest"):
)
-def test_update_webhook_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
-
- # Ensure method has been cached
- assert client._transport.update_webhook in client._transport._wrapped_methods
-
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.update_webhook] = mock_rpc
+def test_create_webhook_rest_error():
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- request = {}
- client.update_webhook(request)
- # Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ gcdc_webhook.UpdateWebhookRequest,
+ dict,
+ ],
+)
+def test_update_webhook_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "webhook": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ }
+ request_init["webhook"] = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4",
+ "display_name": "display_name_value",
+ "generic_web_service": {
+ "uri": "uri_value",
+ "username": "username_value",
+ "password": "password_value",
+ "request_headers": {},
+ "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"],
+ "oauth_config": {
+ "client_id": "client_id_value",
+ "client_secret": "client_secret_value",
+ "token_endpoint": "token_endpoint_value",
+ "scopes": ["scopes_value1", "scopes_value2"],
+ },
+ "service_agent_auth": 1,
+ "webhook_type": 1,
+ "http_method": 1,
+ "request_body": "request_body_value",
+ "parameter_mapping": {},
+ },
+ "service_directory": {"service": "service_value", "generic_web_service": {}},
+ "timeout": {"seconds": 751, "nanos": 543},
+ "disabled": True,
+ }
+ # The version of a generated dependency at test runtime may differ from the version used during generation.
+ # Delete any fields which are not present in the current runtime dependency
+ # See https://github.com/googleapis/gapic-generator-python/issues/1748
+
+ # Determine if the message type is proto-plus or protobuf
+ test_field = gcdc_webhook.UpdateWebhookRequest.meta.fields["webhook"]
+
+ def get_message_fields(field):
+ # Given a field which is a message (composite type), return a list with
+ # all the fields of the message.
+ # If the field is not a composite type, return an empty list.
+ message_fields = []
+
+ if hasattr(field, "message") and field.message:
+ is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+
+ if is_field_type_proto_plus_type:
+ message_fields = field.message.meta.fields.values()
+ # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
+ else: # pragma: NO COVER
+ message_fields = field.message.DESCRIPTOR.fields
+ return message_fields
+
+ runtime_nested_fields = [
+ (field.name, nested_field.name)
+ for field in get_message_fields(test_field)
+ for nested_field in get_message_fields(field)
+ ]
+
+ subfields_not_in_runtime = []
+
+ # For each item in the sample request, create a list of sub fields which are not present at runtime
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for field, value in request_init["webhook"].items(): # pragma: NO COVER
+ result = None
+ is_repeated = False
+ # For repeated fields
+ if isinstance(value, list) and len(value):
+ is_repeated = True
+ result = value[0]
+ # For fields where the type is another message
+ if isinstance(value, dict):
+ result = value
+
+ if result and hasattr(result, "keys"):
+ for subfield in result.keys():
+ if (field, subfield) not in runtime_nested_fields:
+ subfields_not_in_runtime.append(
+ {
+ "field": field,
+ "subfield": subfield,
+ "is_repeated": is_repeated,
+ }
+ )
+
+ # Remove fields from the sample request which are not present in the runtime version of the dependency
+ # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
+ for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
+ field = subfield_to_delete.get("field")
+ field_repeated = subfield_to_delete.get("is_repeated")
+ subfield = subfield_to_delete.get("subfield")
+ if subfield:
+ if field_repeated:
+ for i in range(0, len(request_init["webhook"][field])):
+ del request_init["webhook"][field][i][subfield]
+ else:
+ del request_init["webhook"][field][subfield]
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = gcdc_webhook.Webhook(
+ name="name_value",
+ display_name="display_name_value",
+ disabled=True,
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcdc_webhook.Webhook.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.update_webhook(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcdc_webhook.Webhook)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.disabled is True
+
+
+def test_update_webhook_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_webhook in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_webhook] = mock_rpc
+
+ request = {}
+ client.update_webhook(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
client.update_webhook(request)
@@ -3657,6 +4466,87 @@ def test_update_webhook_rest_unset_required_fields():
assert set(unset_fields) == (set(("updateMask",)) & set(("webhook",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_webhook_rest_interceptors(null_interceptor):
+ transport = transports.WebhooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
+ )
+ client = WebhooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.WebhooksRestInterceptor, "post_update_webhook"
+ ) as post, mock.patch.object(
+ transports.WebhooksRestInterceptor, "pre_update_webhook"
+ ) as pre:
+ pre.assert_not_called()
+ post.assert_not_called()
+ pb_message = gcdc_webhook.UpdateWebhookRequest.pb(
+ gcdc_webhook.UpdateWebhookRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+ req.return_value._content = gcdc_webhook.Webhook.to_json(gcdc_webhook.Webhook())
+
+ request = gcdc_webhook.UpdateWebhookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcdc_webhook.Webhook()
+
+ client.update_webhook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+
+
+def test_update_webhook_rest_bad_request(
+ transport: str = "rest", request_type=gcdc_webhook.UpdateWebhookRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "webhook": {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.update_webhook(request)
+
+
def test_update_webhook_rest_flattened():
client = WebhooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3720,28 +4610,71 @@ def test_update_webhook_rest_flattened_error(transport: str = "rest"):
)
-def test_delete_webhook_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Should wrap all calls on client creation
- assert wrapper_fn.call_count > 0
- wrapper_fn.reset_mock()
+def test_update_webhook_rest_error():
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
- # Ensure method has been cached
- assert client._transport.delete_webhook in client._transport._wrapped_methods
- # Replace cached wrapped function with mock
- mock_rpc = mock.Mock()
- mock_rpc.return_value.name = (
- "foo" # operation_request.operation in compute client(s) expect a string.
- )
- client._transport._wrapped_methods[client._transport.delete_webhook] = mock_rpc
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ webhook.DeleteWebhookRequest,
+ dict,
+ ],
+)
+def test_delete_webhook_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = ""
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ response = client.delete_webhook(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_webhook_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_webhook in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_webhook] = mock_rpc
request = {}
client.delete_webhook(request)
@@ -3836,6 +4769,77 @@ def test_delete_webhook_rest_unset_required_fields():
assert set(unset_fields) == (set(("force",)) & set(("name",)))
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_webhook_rest_interceptors(null_interceptor):
+ transport = transports.WebhooksRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
+ )
+ client = WebhooksClient(transport=transport)
+ with mock.patch.object(
+ type(client.transport._session), "request"
+ ) as req, mock.patch.object(
+ path_template, "transcode"
+ ) as transcode, mock.patch.object(
+ transports.WebhooksRestInterceptor, "pre_delete_webhook"
+ ) as pre:
+ pre.assert_not_called()
+ pb_message = webhook.DeleteWebhookRequest.pb(webhook.DeleteWebhookRequest())
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = Response()
+ req.return_value.status_code = 200
+ req.return_value.request = PreparedRequest()
+
+ request = webhook.DeleteWebhookRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_webhook(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_delete_webhook_rest_bad_request(
+ transport: str = "rest", request_type=webhook.DeleteWebhookRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
+ }
+ request = request_type(**request_init)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.delete_webhook(request)
+
+
def test_delete_webhook_rest_flattened():
client = WebhooksClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3893,6 +4897,12 @@ def test_delete_webhook_rest_flattened_error(transport: str = "rest"):
)
+def test_delete_webhook_rest_error():
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.WebhooksGrpcTransport(
@@ -3982,1459 +4992,21 @@ def test_transport_adc(transport_class):
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
- adc.assert_called_once()
-
-
-def test_transport_kind_grpc():
- transport = WebhooksClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_webhooks_empty_call_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call:
- call.return_value = webhook.ListWebhooksResponse()
- client.list_webhooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.ListWebhooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_webhook_empty_call_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_webhook), "__call__") as call:
- call.return_value = webhook.Webhook()
- client.get_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.GetWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_webhook_empty_call_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_webhook), "__call__") as call:
- call.return_value = gcdc_webhook.Webhook()
- client.create_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.CreateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_webhook_empty_call_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_webhook), "__call__") as call:
- call.return_value = gcdc_webhook.Webhook()
- client.update_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.UpdateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_webhook_empty_call_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call:
- call.return_value = None
- client.delete_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.DeleteWebhookRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = WebhooksAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
-
-def test_initialize_client_w_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_list_webhooks_empty_call_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- webhook.ListWebhooksResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_webhooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.ListWebhooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_get_webhook_empty_call_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_webhook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
- )
- await client.get_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.GetWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_create_webhook_empty_call_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_webhook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
- )
- await client.create_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.CreateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_update_webhook_empty_call_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_webhook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcdc_webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
- )
- await client.update_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.UpdateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-@pytest.mark.asyncio
-async def test_delete_webhook_empty_call_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.DeleteWebhookRequest()
-
- assert args[0] == request_msg
-
-
-def test_transport_kind_rest():
- transport = WebhooksClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
-
-
-def test_list_webhooks_rest_bad_request(request_type=webhook.ListWebhooksRequest):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.list_webhooks(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- webhook.ListWebhooksRequest,
- dict,
- ],
-)
-def test_list_webhooks_rest_call_success(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = webhook.ListWebhooksResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = webhook.ListWebhooksResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.list_webhooks(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListWebhooksPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_webhooks_rest_interceptors(null_interceptor):
- transport = transports.WebhooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
- )
- client = WebhooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.WebhooksRestInterceptor, "post_list_webhooks"
- ) as post, mock.patch.object(
- transports.WebhooksRestInterceptor, "pre_list_webhooks"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = webhook.ListWebhooksRequest.pb(webhook.ListWebhooksRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = webhook.ListWebhooksResponse.to_json(
- webhook.ListWebhooksResponse()
- )
- req.return_value.content = return_value
-
- request = webhook.ListWebhooksRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = webhook.ListWebhooksResponse()
-
- client.list_webhooks(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_webhook_rest_bad_request(request_type=webhook.GetWebhookRequest):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.get_webhook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- webhook.GetWebhookRequest,
- dict,
- ],
-)
-def test_get_webhook_rest_call_success(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = webhook.Webhook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_webhook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, webhook.Webhook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.disabled is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_webhook_rest_interceptors(null_interceptor):
- transport = transports.WebhooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
- )
- client = WebhooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.WebhooksRestInterceptor, "post_get_webhook"
- ) as post, mock.patch.object(
- transports.WebhooksRestInterceptor, "pre_get_webhook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = webhook.GetWebhookRequest.pb(webhook.GetWebhookRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = webhook.Webhook.to_json(webhook.Webhook())
- req.return_value.content = return_value
-
- request = webhook.GetWebhookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = webhook.Webhook()
-
- client.get_webhook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_webhook_rest_bad_request(
- request_type=gcdc_webhook.CreateWebhookRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.create_webhook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_webhook.CreateWebhookRequest,
- dict,
- ],
-)
-def test_create_webhook_rest_call_success(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"}
- request_init["webhook"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "generic_web_service": {
- "uri": "uri_value",
- "username": "username_value",
- "password": "password_value",
- "request_headers": {},
- "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"],
- "oauth_config": {
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- "scopes": ["scopes_value1", "scopes_value2"],
- },
- "service_agent_auth": 1,
- "webhook_type": 1,
- "http_method": 1,
- "request_body": "request_body_value",
- "parameter_mapping": {},
- },
- "service_directory": {"service": "service_value", "generic_web_service": {}},
- "timeout": {"seconds": 751, "nanos": 543},
- "disabled": True,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_webhook.CreateWebhookRequest.meta.fields["webhook"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["webhook"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["webhook"][field])):
- del request_init["webhook"][field][i][subfield]
- else:
- del request_init["webhook"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_webhook.Webhook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.create_webhook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_webhook.Webhook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.disabled is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_webhook_rest_interceptors(null_interceptor):
- transport = transports.WebhooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
- )
- client = WebhooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.WebhooksRestInterceptor, "post_create_webhook"
- ) as post, mock.patch.object(
- transports.WebhooksRestInterceptor, "pre_create_webhook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_webhook.CreateWebhookRequest.pb(
- gcdc_webhook.CreateWebhookRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_webhook.Webhook.to_json(gcdc_webhook.Webhook())
- req.return_value.content = return_value
-
- request = gcdc_webhook.CreateWebhookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_webhook.Webhook()
-
- client.create_webhook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_webhook_rest_bad_request(
- request_type=gcdc_webhook.UpdateWebhookRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "webhook": {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.update_webhook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcdc_webhook.UpdateWebhookRequest,
- dict,
- ],
-)
-def test_update_webhook_rest_call_success(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "webhook": {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- }
- request_init["webhook"] = {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4",
- "display_name": "display_name_value",
- "generic_web_service": {
- "uri": "uri_value",
- "username": "username_value",
- "password": "password_value",
- "request_headers": {},
- "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"],
- "oauth_config": {
- "client_id": "client_id_value",
- "client_secret": "client_secret_value",
- "token_endpoint": "token_endpoint_value",
- "scopes": ["scopes_value1", "scopes_value2"],
- },
- "service_agent_auth": 1,
- "webhook_type": 1,
- "http_method": 1,
- "request_body": "request_body_value",
- "parameter_mapping": {},
- },
- "service_directory": {"service": "service_value", "generic_web_service": {}},
- "timeout": {"seconds": 751, "nanos": 543},
- "disabled": True,
- }
- # The version of a generated dependency at test runtime may differ from the version used during generation.
- # Delete any fields which are not present in the current runtime dependency
- # See https://github.com/googleapis/gapic-generator-python/issues/1748
-
- # Determine if the message type is proto-plus or protobuf
- test_field = gcdc_webhook.UpdateWebhookRequest.meta.fields["webhook"]
-
- def get_message_fields(field):
- # Given a field which is a message (composite type), return a list with
- # all the fields of the message.
- # If the field is not a composite type, return an empty list.
- message_fields = []
-
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
-
- if is_field_type_proto_plus_type:
- message_fields = field.message.meta.fields.values()
- # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types
- else: # pragma: NO COVER
- message_fields = field.message.DESCRIPTOR.fields
- return message_fields
-
- runtime_nested_fields = [
- (field.name, nested_field.name)
- for field in get_message_fields(test_field)
- for nested_field in get_message_fields(field)
- ]
-
- subfields_not_in_runtime = []
-
- # For each item in the sample request, create a list of sub fields which are not present at runtime
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for field, value in request_init["webhook"].items(): # pragma: NO COVER
- result = None
- is_repeated = False
- # For repeated fields
- if isinstance(value, list) and len(value):
- is_repeated = True
- result = value[0]
- # For fields where the type is another message
- if isinstance(value, dict):
- result = value
-
- if result and hasattr(result, "keys"):
- for subfield in result.keys():
- if (field, subfield) not in runtime_nested_fields:
- subfields_not_in_runtime.append(
- {
- "field": field,
- "subfield": subfield,
- "is_repeated": is_repeated,
- }
- )
-
- # Remove fields from the sample request which are not present in the runtime version of the dependency
- # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime
- for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER
- field = subfield_to_delete.get("field")
- field_repeated = subfield_to_delete.get("is_repeated")
- subfield = subfield_to_delete.get("subfield")
- if subfield:
- if field_repeated:
- for i in range(0, len(request_init["webhook"][field])):
- del request_init["webhook"][field][i][subfield]
- else:
- del request_init["webhook"][field][subfield]
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = gcdc_webhook.Webhook(
- name="name_value",
- display_name="display_name_value",
- disabled=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcdc_webhook.Webhook.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.update_webhook(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcdc_webhook.Webhook)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.disabled is True
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_webhook_rest_interceptors(null_interceptor):
- transport = transports.WebhooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
- )
- client = WebhooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.WebhooksRestInterceptor, "post_update_webhook"
- ) as post, mock.patch.object(
- transports.WebhooksRestInterceptor, "pre_update_webhook"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcdc_webhook.UpdateWebhookRequest.pb(
- gcdc_webhook.UpdateWebhookRequest()
- )
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
- return_value = gcdc_webhook.Webhook.to_json(gcdc_webhook.Webhook())
- req.return_value.content = return_value
-
- request = gcdc_webhook.UpdateWebhookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = gcdc_webhook.Webhook()
-
- client.update_webhook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_webhook_rest_bad_request(request_type=webhook.DeleteWebhookRequest):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = mock.Mock()
- req.return_value = response_value
- client.delete_webhook(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- webhook.DeleteWebhookRequest,
- dict,
- ],
-)
-def test_delete_webhook_rest_call_success(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/agents/sample3/webhooks/sample4"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = ""
- response_value.content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.delete_webhook(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_webhook_rest_interceptors(null_interceptor):
- transport = transports.WebhooksRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None if null_interceptor else transports.WebhooksRestInterceptor(),
- )
- client = WebhooksClient(transport=transport)
-
- with mock.patch.object(
- type(client.transport._session), "request"
- ) as req, mock.patch.object(
- path_template, "transcode"
- ) as transcode, mock.patch.object(
- transports.WebhooksRestInterceptor, "pre_delete_webhook"
- ) as pre:
- pre.assert_not_called()
- pb_message = webhook.DeleteWebhookRequest.pb(webhook.DeleteWebhookRequest())
- transcode.return_value = {
- "method": "post",
- "uri": "my_uri",
- "body": pb_message,
- "query_params": pb_message,
- }
-
- req.return_value = mock.Mock()
- req.return_value.status_code = 200
-
- request = webhook.DeleteWebhookRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
-
- client.delete_webhook(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
-
-
-def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_location(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.GetLocationRequest,
- dict,
- ],
-)
-def test_get_location_rest(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_location(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
-
-
-def test_list_locations_rest_bad_request(
- request_type=locations_pb2.ListLocationsRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_locations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- locations_pb2.ListLocationsRequest,
- dict,
- ],
-)
-def test_list_locations_rest(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_cancel_operation_rest_bad_request(
- request_type=operations_pb2.CancelOperationRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.cancel_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.cancel_operation(request)
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_get_operation_rest_bad_request(
- request_type=operations_pb2.GetOperationRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/operations/sample2"}, request
- )
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_operation(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1/operations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.get_operation(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
-
-
-def test_list_operations_rest_bad_request(
- request_type=operations_pb2.ListOperationsRequest,
-):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- json_return_value = ""
- response_value.json = mock.Mock(return_value={})
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_operations(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # Wrap the value into a proper Response obj
- response_value = mock.Mock()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value.content = json_return_value.encode("UTF-8")
-
- req.return_value = response_value
-
- response = client.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
-
-
-def test_initialize_client_w_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- assert client is not None
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_list_webhooks_empty_call_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call:
- client.list_webhooks(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.ListWebhooksRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_get_webhook_empty_call_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_webhook), "__call__") as call:
- client.get_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.GetWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_create_webhook_empty_call_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_webhook), "__call__") as call:
- client.create_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.CreateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_update_webhook_empty_call_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_webhook), "__call__") as call:
- client.update_webhook(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = gcdc_webhook.UpdateWebhookRequest()
-
- assert args[0] == request_msg
-
-
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
-def test_delete_webhook_empty_call_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call:
- client.delete_webhook(request=None)
+ adc.assert_called_once()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = webhook.DeleteWebhookRequest()
- assert args[0] == request_msg
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "rest",
+ ],
+)
+def test_transport_kind(transport_name):
+ transport = WebhooksClient.get_transport_class(transport_name)(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert transport.kind == transport_name
def test_transport_grpc_default():
@@ -5955,115 +5527,415 @@ def test_parse_common_billing_account_path():
}
path = WebhooksClient.common_billing_account_path(**expected)
- # Check that the path construction is reversible.
- actual = WebhooksClient.parse_common_billing_account_path(path)
- assert expected == actual
+ # Check that the path construction is reversible.
+ actual = WebhooksClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = WebhooksClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = WebhooksClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WebhooksClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = WebhooksClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nautilus",
+ }
+ path = WebhooksClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WebhooksClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "scallop"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = WebhooksClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "abalone",
+ }
+ path = WebhooksClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WebhooksClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = WebhooksClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = WebhooksClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WebhooksClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.WebhooksTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.WebhooksTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = WebhooksClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = WebhooksAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_get_location_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.GetLocationRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/locations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_location(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.GetLocationRequest,
+ dict,
+ ],
+)
+def test_get_location_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1/locations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.Location()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.get_location(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.Location)
+
+
+def test_list_locations_rest_bad_request(
+ transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_locations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ locations_pb2.ListLocationsRequest,
+ dict,
+ ],
+)
+def test_list_locations_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = locations_pb2.ListLocationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+
+ response = client.list_locations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, locations_pb2.ListLocationsResponse)
+
+
+def test_cancel_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.cancel_operation(request)
-def test_common_folder_path():
- folder = "cuttlefish"
- expected = "folders/{folder}".format(
- folder=folder,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = WebhooksClient.common_folder_path(folder)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = "{}"
-def test_parse_common_folder_path():
- expected = {
- "folder": "mussel",
- }
- path = WebhooksClient.common_folder_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = WebhooksClient.parse_common_folder_path(path)
- assert expected == actual
+ response = client.cancel_operation(request)
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_common_organization_path():
- organization = "winkle"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = WebhooksClient.common_organization_path(organization)
- assert expected == actual
+def test_get_operation_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.GetOperationRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
-def test_parse_common_organization_path():
- expected = {
- "organization": "nautilus",
- }
- path = WebhooksClient.common_organization_path(**expected)
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
- # Check that the path construction is reversible.
- actual = WebhooksClient.parse_common_organization_path(path)
- assert expected == actual
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.get_operation(request)
-def test_common_project_path():
- project = "scallop"
- expected = "projects/{project}".format(
- project=project,
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- actual = WebhooksClient.common_project_path(project)
- assert expected == actual
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
-def test_parse_common_project_path():
- expected = {
- "project": "abalone",
- }
- path = WebhooksClient.common_project_path(**expected)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- # Check that the path construction is reversible.
- actual = WebhooksClient.parse_common_project_path(path)
- assert expected == actual
+ response = client.get_operation(request)
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
-def test_common_location_path():
- project = "squid"
- location = "clam"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+def test_list_operations_rest_bad_request(
+ transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
+):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = WebhooksClient.common_location_path(project, location)
- assert expected == actual
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
-def test_parse_common_location_path():
- expected = {
- "project": "whelk",
- "location": "octopus",
- }
- path = WebhooksClient.common_location_path(**expected)
+ # Mock the http request call within the method and fake a BadRequest error.
+ with mock.patch.object(Session, "request") as req, pytest.raises(
+ core_exceptions.BadRequest
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ client.list_operations(request)
- # Check that the path construction is reversible.
- actual = WebhooksClient.parse_common_location_path(path)
- assert expected == actual
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(type(client.transport._session), "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
- with mock.patch.object(
- transports.WebhooksTransport, "_prep_wrapped_messages"
- ) as prep:
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
- with mock.patch.object(
- transports.WebhooksTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = WebhooksClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
def test_cancel_operation(transport: str = "grpc"):
@@ -6093,7 +5965,7 @@ def test_cancel_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6146,7 +6018,7 @@ def test_cancel_operation_field_headers():
@pytest.mark.asyncio
async def test_cancel_operation_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6191,7 +6063,7 @@ def test_cancel_operation_from_dict():
@pytest.mark.asyncio
async def test_cancel_operation_from_dict_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
@@ -6232,7 +6104,7 @@ def test_get_operation(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_operation_async(transport: str = "grpc_asyncio"):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6287,7 +6159,7 @@ def test_get_operation_field_headers():
@pytest.mark.asyncio
async def test_get_operation_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6334,7 +6206,7 @@ def test_get_operation_from_dict():
@pytest.mark.asyncio
async def test_get_operation_from_dict_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
@@ -6377,7 +6249,7 @@ def test_list_operations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_operations_async(transport: str = "grpc_asyncio"):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6432,7 +6304,7 @@ def test_list_operations_field_headers():
@pytest.mark.asyncio
async def test_list_operations_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6479,7 +6351,7 @@ def test_list_operations_from_dict():
@pytest.mark.asyncio
async def test_list_operations_from_dict_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
@@ -6522,7 +6394,7 @@ def test_list_locations(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_list_locations_async(transport: str = "grpc_asyncio"):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6577,7 +6449,7 @@ def test_list_locations_field_headers():
@pytest.mark.asyncio
async def test_list_locations_field_headers_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -6624,7 +6496,7 @@ def test_list_locations_from_dict():
@pytest.mark.asyncio
async def test_list_locations_from_dict_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6667,7 +6539,7 @@ def test_get_location(transport: str = "grpc"):
@pytest.mark.asyncio
async def test_get_location_async(transport: str = "grpc_asyncio"):
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
@@ -6719,7 +6591,7 @@ def test_get_location_field_headers():
@pytest.mark.asyncio
async def test_get_location_field_headers_async():
- client = WebhooksAsyncClient(credentials=async_anonymous_credentials())
+ client = WebhooksAsyncClient(credentials=ga_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.
@@ -6765,7 +6637,7 @@ def test_get_location_from_dict():
@pytest.mark.asyncio
async def test_get_location_from_dict_async():
client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_locations), "__call__") as call:
@@ -6781,41 +6653,22 @@ async def test_get_location_from_dict_async():
call.assert_called()
-def test_transport_close_grpc():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
-@pytest.mark.asyncio
-async def test_transport_close_grpc_asyncio():
- client = WebhooksAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
-
+def test_transport_close():
+ transports = {
+ "rest": "_session",
+ "grpc": "_grpc_channel",
+ }
-def test_transport_close_rest():
- client = WebhooksClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- with mock.patch.object(
- type(getattr(client.transport, "_session")), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ for transport, close_name in transports.items():
+ client = WebhooksClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, close_name)), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
diff --git a/packages/google-cloud-discoveryengine/.flake8 b/packages/google-cloud-discoveryengine/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-discoveryengine/.flake8
+++ b/packages/google-cloud-discoveryengine/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-discoveryengine/CONTRIBUTING.rst b/packages/google-cloud-discoveryengine/CONTRIBUTING.rst
index b518420776dd..bdbfde8a3a39 100644
--- a/packages/google-cloud-discoveryengine/CONTRIBUTING.rst
+++ b/packages/google-cloud-discoveryengine/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-discoveryengine/MANIFEST.in b/packages/google-cloud-discoveryengine/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-discoveryengine/MANIFEST.in
+++ b/packages/google-cloud-discoveryengine/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-discoveryengine/docs/conf.py b/packages/google-cloud-discoveryengine/docs/conf.py
index 5d9e852844e9..b25105cd3957 100644
--- a/packages/google-cloud-discoveryengine/docs/conf.py
+++ b/packages/google-cloud-discoveryengine/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py
index f63305c8cf9e..558c8aab67c5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.13.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py
index f63305c8cf9e..558c8aab67c5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.13.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
index d71f89ec7f79..dca1bedd0ca3 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest.py
index a0179ceb8455..15a0222885cb 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py
index 9345a949c7ec..6ebec98c4e41 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
index f4699dffaf43..150a1789a868 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
index b27ceddf8b5a..764ebdee543a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
@@ -50,7 +50,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
index 2252155c4e36..db44fea2ed66 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest.py
index 5a5e52373f7f..da8184d34e91 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
index 0364f36bac99..46606d750aa9 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest.py
index 5e554f2b6f9f..6619b9e7503c 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest.py
index e0178094cfc1..61864b0d3f67 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
index baec83220690..2f318767d078 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py
index c9469c9338df..24ac50620e10 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
index c115b047505f..fbc4c914c234 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
index e956b04266aa..925d2df8571a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
index 61ffd5559e39..d07076ce3dad 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py
index f63305c8cf9e..558c8aab67c5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.13.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py
index 5e4d52d1fd69..a8d8addbf7cf 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py
index 2bcbabdc0e05..fe95bbfe97a8 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py
index 01b955f43ddb..bf6947b98372 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py
index 23f720d26415..a2f838c2e6de 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py
index 17970a3776e1..5b0d12dbe654 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py
index e6494c34d69a..c6ead005b7fa 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py
index 30d2f92fe63d..5d16784caf4f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py
@@ -50,7 +50,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py
index b6a17c008cbd..9dc083baa4a1 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py
index a003913a2b16..fdf854939dcc 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py
index 1668b4278ded..0eb80b3ebcd5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py
index 1e13815ac599..ab6a58e48a20 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py
index 2bc93e9bf372..17e22273061f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py
index 3acc69dac777..b9fcc7578477 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py
index beb0cd04ad97..aab9a6c67927 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py
index aee0804c5499..bdf953fdc5dd 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py
index be2c1632cc26..5f19967c2e3e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py
@@ -48,7 +48,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py
index b36513857a2a..93c612a241b2 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py
index a2fcdf7d40de..88b5024323d6 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py
index 39bf5db6df93..c838a979f667 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py
index 89a85763ef6c..7e75237178c6 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py
index 8e48beed5cea..01e1a927df4d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py
index a4e77e38d2a6..f30713bea56c 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py
index f63305c8cf9e..558c8aab67c5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.13.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py
index 4777d72ea0ed..3647d42c1fbe 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py
index 2c8322afe9b0..6d8fbbbde126 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py
index e0f7056321da..134d6b55824c 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py
index 63dd1dbc6149..362034856f6e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/data_store_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py
index bcbb46f9ad15..6a77bbd5fa20 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py
@@ -50,7 +50,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py
index cb21112f114e..fcb97245fa7e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py
index 02aaf00bf26d..1dd76f32cc8d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/evaluation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py
index ca09ef181b8e..aca1a6e6f209 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py
index 952e940cfe2d..4827248c0d25 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/project_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py
index 1ffdc1b11219..6fc2c5eb8202 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/rank_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py
index b4c8690f562b..2c8f1404ea81 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py
index bbfd1b419649..d1fd8e392df5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py
index 2e0c3e87fa56..bfec782a92b0 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/sample_query_set_service/transports/rest.py
@@ -48,7 +48,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py
index 3e511cdb21fb..d92f433fb7da 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py
index 96c97f667847..7101cf839bc8 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py
index 028a2b211f46..b641b0af3c2b 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_tuning_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py
index fd109c9b7741..692d8a044509 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/transports/rest.py
@@ -47,7 +47,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py
index 9c47be54f13f..18465042b88e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py
@@ -46,7 +46,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py
index 43f49c6013f3..93f4f0f45ffe 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py
@@ -49,7 +49,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-discoveryengine/noxfile.py b/packages/google-cloud-discoveryengine/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-discoveryengine/noxfile.py
+++ b/packages/google-cloud-discoveryengine/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
index 6809098fb201..515c7525e32a 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-discoveryengine",
- "version": "0.13.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json
index 86def45fa531..4d014b08daf6 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-discoveryengine",
- "version": "0.13.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json
index 828bdc4c7119..c8efdd7d5106 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-discoveryengine",
- "version": "0.13.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/packages/google-cloud-discoveryengine/scripts/decrypt-secrets.sh b/packages/google-cloud-discoveryengine/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-discoveryengine/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-discoveryengine/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-discoveryengine/setup.py b/packages/google-cloud-discoveryengine/setup.py
index a2ea2eac381d..dad4e428d99f 100644
--- a/packages/google-cloud-discoveryengine/setup.py
+++ b/packages/google-cloud-discoveryengine/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-discoveryengine/testing/constraints-3.13.txt b/packages/google-cloud-discoveryengine/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-dlp/.flake8 b/packages/google-cloud-dlp/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-dlp/.flake8
+++ b/packages/google-cloud-dlp/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dlp/CONTRIBUTING.rst b/packages/google-cloud-dlp/CONTRIBUTING.rst
index 27078ee7164d..badd5bc280e7 100644
--- a/packages/google-cloud-dlp/CONTRIBUTING.rst
+++ b/packages/google-cloud-dlp/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-dlp/MANIFEST.in b/packages/google-cloud-dlp/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-dlp/MANIFEST.in
+++ b/packages/google-cloud-dlp/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dlp/docs/conf.py b/packages/google-cloud-dlp/docs/conf.py
index 4418563f8f48..eb85981e644a 100644
--- a/packages/google-cloud-dlp/docs/conf.py
+++ b/packages/google-cloud-dlp/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py
index 22dde061b013..558c8aab67c5 100644
--- a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py
+++ b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "3.24.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py
index 22dde061b013..558c8aab67c5 100644
--- a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py
+++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "3.24.0" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/services/dlp_service/transports/rest.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/services/dlp_service/transports/rest.py
index 70e76100eafd..2b7211d97505 100644
--- a/packages/google-cloud-dlp/google/cloud/dlp_v2/services/dlp_service/transports/rest.py
+++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/services/dlp_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-dlp/noxfile.py b/packages/google-cloud-dlp/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-dlp/noxfile.py
+++ b/packages/google-cloud-dlp/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json
index b4acf1b1efc9..4da85d5c6cd9 100644
--- a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json
+++ b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-dlp",
- "version": "3.24.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/packages/google-cloud-dlp/scripts/decrypt-secrets.sh b/packages/google-cloud-dlp/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-dlp/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-dlp/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-dlp/setup.py b/packages/google-cloud-dlp/setup.py
index 156a95f391ed..90d3d680f275 100644
--- a/packages/google-cloud-dlp/setup.py
+++ b/packages/google-cloud-dlp/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -82,6 +83,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-dlp/testing/constraints-3.13.txt b/packages/google-cloud-dlp/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-dlp/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-edgenetwork/.flake8 b/packages/google-cloud-edgenetwork/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-edgenetwork/.flake8
+++ b/packages/google-cloud-edgenetwork/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-edgenetwork/CONTRIBUTING.rst b/packages/google-cloud-edgenetwork/CONTRIBUTING.rst
index 3914b5d816ff..3d645a075025 100644
--- a/packages/google-cloud-edgenetwork/CONTRIBUTING.rst
+++ b/packages/google-cloud-edgenetwork/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-edgenetwork/MANIFEST.in b/packages/google-cloud-edgenetwork/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-edgenetwork/MANIFEST.in
+++ b/packages/google-cloud-edgenetwork/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-edgenetwork/docs/conf.py b/packages/google-cloud-edgenetwork/docs/conf.py
index 036f7db03b23..8b22d6c0175f 100644
--- a/packages/google-cloud-edgenetwork/docs/conf.py
+++ b/packages/google-cloud-edgenetwork/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/services/edge_network/transports/rest.py b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/services/edge_network/transports/rest.py
index aed8a6bf6685..ff9c73ccdb06 100644
--- a/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/services/edge_network/transports/rest.py
+++ b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/services/edge_network/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-edgenetwork/noxfile.py b/packages/google-cloud-edgenetwork/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-edgenetwork/noxfile.py
+++ b/packages/google-cloud-edgenetwork/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-edgenetwork/scripts/decrypt-secrets.sh b/packages/google-cloud-edgenetwork/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-edgenetwork/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-edgenetwork/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-edgenetwork/setup.py b/packages/google-cloud-edgenetwork/setup.py
index 30e7f68fba63..056bc9eed4db 100644
--- a/packages/google-cloud-edgenetwork/setup.py
+++ b/packages/google-cloud-edgenetwork/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-edgenetwork/testing/constraints-3.13.txt b/packages/google-cloud-edgenetwork/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-edgenetwork/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-enterpriseknowledgegraph/.flake8 b/packages/google-cloud-enterpriseknowledgegraph/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/.flake8
+++ b/packages/google-cloud-enterpriseknowledgegraph/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-enterpriseknowledgegraph/CONTRIBUTING.rst b/packages/google-cloud-enterpriseknowledgegraph/CONTRIBUTING.rst
index 16e81762554a..9ab8012d3be0 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/CONTRIBUTING.rst
+++ b/packages/google-cloud-enterpriseknowledgegraph/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-enterpriseknowledgegraph/MANIFEST.in b/packages/google-cloud-enterpriseknowledgegraph/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/MANIFEST.in
+++ b/packages/google-cloud-enterpriseknowledgegraph/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-enterpriseknowledgegraph/docs/conf.py b/packages/google-cloud-enterpriseknowledgegraph/docs/conf.py
index 931eaabd7b56..2deed88d9506 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/docs/conf.py
+++ b/packages/google-cloud-enterpriseknowledgegraph/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/services/enterprise_knowledge_graph_service/transports/rest.py b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/services/enterprise_knowledge_graph_service/transports/rest.py
index a96c4096e26d..cff1568452e5 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/services/enterprise_knowledge_graph_service/transports/rest.py
+++ b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/services/enterprise_knowledge_graph_service/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-enterpriseknowledgegraph/noxfile.py b/packages/google-cloud-enterpriseknowledgegraph/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/noxfile.py
+++ b/packages/google-cloud-enterpriseknowledgegraph/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-enterpriseknowledgegraph/scripts/decrypt-secrets.sh b/packages/google-cloud-enterpriseknowledgegraph/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-enterpriseknowledgegraph/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-enterpriseknowledgegraph/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-enterpriseknowledgegraph/setup.py b/packages/google-cloud-enterpriseknowledgegraph/setup.py
index 10d8a8128d2e..e5e74fe6417a 100644
--- a/packages/google-cloud-enterpriseknowledgegraph/setup.py
+++ b/packages/google-cloud-enterpriseknowledgegraph/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-enterpriseknowledgegraph/testing/constraints-3.13.txt b/packages/google-cloud-enterpriseknowledgegraph/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-enterpriseknowledgegraph/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-essential-contacts/.flake8 b/packages/google-cloud-essential-contacts/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-essential-contacts/.flake8
+++ b/packages/google-cloud-essential-contacts/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-essential-contacts/CONTRIBUTING.rst b/packages/google-cloud-essential-contacts/CONTRIBUTING.rst
index e03b03f50913..3a889935ac25 100644
--- a/packages/google-cloud-essential-contacts/CONTRIBUTING.rst
+++ b/packages/google-cloud-essential-contacts/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-essential-contacts/MANIFEST.in b/packages/google-cloud-essential-contacts/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-essential-contacts/MANIFEST.in
+++ b/packages/google-cloud-essential-contacts/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-essential-contacts/docs/conf.py b/packages/google-cloud-essential-contacts/docs/conf.py
index 8d0cf6f90556..68802e4aea12 100644
--- a/packages/google-cloud-essential-contacts/docs/conf.py
+++ b/packages/google-cloud-essential-contacts/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py
index 27263f6fa9e6..558c8aab67c5 100644
--- a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py
+++ b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.7.6" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py
index 27263f6fa9e6..558c8aab67c5 100644
--- a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py
+++ b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.7.6" # {x-release-please-version}
+__version__ = "0.0.0" # {x-release-please-version}
diff --git a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py
index 90ef69c7c788..9d4a9cc8c02f 100644
--- a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py
+++ b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/services/essential_contacts_service/transports/rest.py
@@ -42,7 +42,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-essential-contacts/noxfile.py b/packages/google-cloud-essential-contacts/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-essential-contacts/noxfile.py
+++ b/packages/google-cloud-essential-contacts/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json b/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json
index 9f7c4971dd83..5c3df15cfed5 100644
--- a/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json
+++ b/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-essential-contacts",
- "version": "1.7.6"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/packages/google-cloud-essential-contacts/scripts/decrypt-secrets.sh b/packages/google-cloud-essential-contacts/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-essential-contacts/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-essential-contacts/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-essential-contacts/setup.py b/packages/google-cloud-essential-contacts/setup.py
index be9eebf825ad..a1f7c8034963 100644
--- a/packages/google-cloud-essential-contacts/setup.py
+++ b/packages/google-cloud-essential-contacts/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-essential-contacts/testing/constraints-3.13.txt b/packages/google-cloud-essential-contacts/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-essential-contacts/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-eventarc-publishing/.flake8 b/packages/google-cloud-eventarc-publishing/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-eventarc-publishing/.flake8
+++ b/packages/google-cloud-eventarc-publishing/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc-publishing/CONTRIBUTING.rst b/packages/google-cloud-eventarc-publishing/CONTRIBUTING.rst
index 405c4da68b34..6a00cb6cc150 100644
--- a/packages/google-cloud-eventarc-publishing/CONTRIBUTING.rst
+++ b/packages/google-cloud-eventarc-publishing/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-eventarc-publishing/MANIFEST.in b/packages/google-cloud-eventarc-publishing/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-eventarc-publishing/MANIFEST.in
+++ b/packages/google-cloud-eventarc-publishing/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc-publishing/docs/conf.py b/packages/google-cloud-eventarc-publishing/docs/conf.py
index 40c00f32d8c0..80b1e5b67fab 100644
--- a/packages/google-cloud-eventarc-publishing/docs/conf.py
+++ b/packages/google-cloud-eventarc-publishing/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py
index 08738a587f06..69c528a8de45 100644
--- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py
+++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-eventarc-publishing/noxfile.py b/packages/google-cloud-eventarc-publishing/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-eventarc-publishing/noxfile.py
+++ b/packages/google-cloud-eventarc-publishing/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-eventarc-publishing/scripts/decrypt-secrets.sh b/packages/google-cloud-eventarc-publishing/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-eventarc-publishing/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-eventarc-publishing/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-eventarc-publishing/setup.py b/packages/google-cloud-eventarc-publishing/setup.py
index a0ee22dcd628..9ee0f11a0483 100644
--- a/packages/google-cloud-eventarc-publishing/setup.py
+++ b/packages/google-cloud-eventarc-publishing/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-eventarc-publishing/testing/constraints-3.13.txt b/packages/google-cloud-eventarc-publishing/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-eventarc-publishing/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-eventarc/.flake8 b/packages/google-cloud-eventarc/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-eventarc/.flake8
+++ b/packages/google-cloud-eventarc/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc/CONTRIBUTING.rst b/packages/google-cloud-eventarc/CONTRIBUTING.rst
index 85ee75e0ef0c..f308f0ab5ffc 100644
--- a/packages/google-cloud-eventarc/CONTRIBUTING.rst
+++ b/packages/google-cloud-eventarc/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-eventarc/MANIFEST.in b/packages/google-cloud-eventarc/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-eventarc/MANIFEST.in
+++ b/packages/google-cloud-eventarc/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc/docs/conf.py b/packages/google-cloud-eventarc/docs/conf.py
index a2424a4abf60..2ebb2c793a77 100644
--- a/packages/google-cloud-eventarc/docs/conf.py
+++ b/packages/google-cloud-eventarc/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py
index 682fa947f594..97082866535e 100644
--- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py
+++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py
@@ -55,7 +55,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-eventarc/noxfile.py b/packages/google-cloud-eventarc/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-eventarc/noxfile.py
+++ b/packages/google-cloud-eventarc/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-eventarc/scripts/decrypt-secrets.sh b/packages/google-cloud-eventarc/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-eventarc/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-eventarc/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-eventarc/setup.py b/packages/google-cloud-eventarc/setup.py
index 303bfe04c621..f6dd8253e2b8 100644
--- a/packages/google-cloud-eventarc/setup.py
+++ b/packages/google-cloud-eventarc/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -83,6 +84,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-eventarc/testing/constraints-3.13.txt b/packages/google-cloud-eventarc/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-eventarc/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-filestore/.flake8 b/packages/google-cloud-filestore/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-filestore/.flake8
+++ b/packages/google-cloud-filestore/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-filestore/CONTRIBUTING.rst b/packages/google-cloud-filestore/CONTRIBUTING.rst
index db3d78268c71..9aad228435f8 100644
--- a/packages/google-cloud-filestore/CONTRIBUTING.rst
+++ b/packages/google-cloud-filestore/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-filestore/MANIFEST.in b/packages/google-cloud-filestore/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-filestore/MANIFEST.in
+++ b/packages/google-cloud-filestore/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-filestore/docs/conf.py b/packages/google-cloud-filestore/docs/conf.py
index 3c192002e02b..3214404f3091 100644
--- a/packages/google-cloud-filestore/docs/conf.py
+++ b/packages/google-cloud-filestore/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-filestore/google/cloud/filestore_v1/services/cloud_filestore_manager/transports/rest.py b/packages/google-cloud-filestore/google/cloud/filestore_v1/services/cloud_filestore_manager/transports/rest.py
index 8c23d9bce5c9..5361f376ea56 100644
--- a/packages/google-cloud-filestore/google/cloud/filestore_v1/services/cloud_filestore_manager/transports/rest.py
+++ b/packages/google-cloud-filestore/google/cloud/filestore_v1/services/cloud_filestore_manager/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-filestore/noxfile.py b/packages/google-cloud-filestore/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-filestore/noxfile.py
+++ b/packages/google-cloud-filestore/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-filestore/scripts/decrypt-secrets.sh b/packages/google-cloud-filestore/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-filestore/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-filestore/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-filestore/setup.py b/packages/google-cloud-filestore/setup.py
index 9a13264200c9..819dce879389 100644
--- a/packages/google-cloud-filestore/setup.py
+++ b/packages/google-cloud-filestore/setup.py
@@ -45,6 +45,7 @@
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"google-cloud-common >= 1.0.0, <2.0.0dev",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -83,6 +84,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-filestore/testing/constraints-3.13.txt b/packages/google-cloud-filestore/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-filestore/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-functions/.flake8 b/packages/google-cloud-functions/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-functions/.flake8
+++ b/packages/google-cloud-functions/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-functions/CONTRIBUTING.rst b/packages/google-cloud-functions/CONTRIBUTING.rst
index c89cbc875239..074eae65e1fb 100644
--- a/packages/google-cloud-functions/CONTRIBUTING.rst
+++ b/packages/google-cloud-functions/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-functions/MANIFEST.in b/packages/google-cloud-functions/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-functions/MANIFEST.in
+++ b/packages/google-cloud-functions/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-functions/docs/conf.py b/packages/google-cloud-functions/docs/conf.py
index d2cd3ac0563d..95e08a879e78 100644
--- a/packages/google-cloud-functions/docs/conf.py
+++ b/packages/google-cloud-functions/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py
index df132aaa6d9e..d90df0bca9b0 100644
--- a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py
+++ b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/rest.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/rest.py
index 7d2a7d6dcf85..04388fe090fd 100644
--- a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/rest.py
+++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/rest.py
@@ -45,7 +45,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-functions/noxfile.py b/packages/google-cloud-functions/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-functions/noxfile.py
+++ b/packages/google-cloud-functions/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-functions/scripts/decrypt-secrets.sh b/packages/google-cloud-functions/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-functions/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-functions/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-functions/setup.py b/packages/google-cloud-functions/setup.py
index eae6c099d2ac..4ff91ff458ee 100644
--- a/packages/google-cloud-functions/setup.py
+++ b/packages/google-cloud-functions/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -83,6 +84,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-functions/testing/constraints-3.13.txt b/packages/google-cloud-functions/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-functions/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-gdchardwaremanagement/.flake8 b/packages/google-cloud-gdchardwaremanagement/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-gdchardwaremanagement/.flake8
+++ b/packages/google-cloud-gdchardwaremanagement/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gdchardwaremanagement/CONTRIBUTING.rst b/packages/google-cloud-gdchardwaremanagement/CONTRIBUTING.rst
index e2d3e9b6bd53..8fdb2cc382e4 100644
--- a/packages/google-cloud-gdchardwaremanagement/CONTRIBUTING.rst
+++ b/packages/google-cloud-gdchardwaremanagement/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-gdchardwaremanagement/MANIFEST.in b/packages/google-cloud-gdchardwaremanagement/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-gdchardwaremanagement/MANIFEST.in
+++ b/packages/google-cloud-gdchardwaremanagement/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gdchardwaremanagement/docs/conf.py b/packages/google-cloud-gdchardwaremanagement/docs/conf.py
index ecb8de7d3ca8..5e15f162639b 100644
--- a/packages/google-cloud-gdchardwaremanagement/docs/conf.py
+++ b/packages/google-cloud-gdchardwaremanagement/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gdchardwaremanagement/google/cloud/gdchardwaremanagement_v1alpha/services/gdc_hardware_management/transports/rest.py b/packages/google-cloud-gdchardwaremanagement/google/cloud/gdchardwaremanagement_v1alpha/services/gdc_hardware_management/transports/rest.py
index 9371bc6e0b76..96a250ec267e 100644
--- a/packages/google-cloud-gdchardwaremanagement/google/cloud/gdchardwaremanagement_v1alpha/services/gdc_hardware_management/transports/rest.py
+++ b/packages/google-cloud-gdchardwaremanagement/google/cloud/gdchardwaremanagement_v1alpha/services/gdc_hardware_management/transports/rest.py
@@ -43,7 +43,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-gdchardwaremanagement/noxfile.py b/packages/google-cloud-gdchardwaremanagement/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-gdchardwaremanagement/noxfile.py
+++ b/packages/google-cloud-gdchardwaremanagement/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-gdchardwaremanagement/scripts/decrypt-secrets.sh b/packages/google-cloud-gdchardwaremanagement/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-gdchardwaremanagement/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-gdchardwaremanagement/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-gdchardwaremanagement/setup.py b/packages/google-cloud-gdchardwaremanagement/setup.py
index 7730f3705da1..5bb89c380cf3 100644
--- a/packages/google-cloud-gdchardwaremanagement/setup.py
+++ b/packages/google-cloud-gdchardwaremanagement/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-gdchardwaremanagement/testing/constraints-3.13.txt b/packages/google-cloud-gdchardwaremanagement/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-gdchardwaremanagement/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/packages/google-cloud-gke-backup/.flake8 b/packages/google-cloud-gke-backup/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-gke-backup/.flake8
+++ b/packages/google-cloud-gke-backup/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-backup/CONTRIBUTING.rst b/packages/google-cloud-gke-backup/CONTRIBUTING.rst
index d85f5b725d6f..db1d7ccabc54 100644
--- a/packages/google-cloud-gke-backup/CONTRIBUTING.rst
+++ b/packages/google-cloud-gke-backup/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-gke-backup/MANIFEST.in b/packages/google-cloud-gke-backup/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-gke-backup/MANIFEST.in
+++ b/packages/google-cloud-gke-backup/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-backup/docs/conf.py b/packages/google-cloud-gke-backup/docs/conf.py
index f49d1683356b..3bff951b2bda 100644
--- a/packages/google-cloud-gke-backup/docs/conf.py
+++ b/packages/google-cloud-gke-backup/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/services/backup_for_gke/transports/rest.py b/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/services/backup_for_gke/transports/rest.py
index f295b0337979..a34f4839b8ce 100644
--- a/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/services/backup_for_gke/transports/rest.py
+++ b/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/services/backup_for_gke/transports/rest.py
@@ -52,7 +52,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-gke-backup/noxfile.py b/packages/google-cloud-gke-backup/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-gke-backup/noxfile.py
+++ b/packages/google-cloud-gke-backup/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-gke-backup/scripts/decrypt-secrets.sh b/packages/google-cloud-gke-backup/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-gke-backup/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-gke-backup/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-gke-backup/setup.py b/packages/google-cloud-gke-backup/setup.py
index 3033cb3239be..05f5fe816d3e 100644
--- a/packages/google-cloud-gke-backup/setup.py
+++ b/packages/google-cloud-gke-backup/setup.py
@@ -44,6 +44,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >= 0.12.4, <1.0.0dev",
]
@@ -83,6 +84,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-gke-backup/testing/constraints-3.13.txt b/packages/google-cloud-gke-backup/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ad3f0fa58e2d
--- /dev/null
+++ b/packages/google-cloud-gke-backup/testing/constraints-3.13.txt
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
+grpc-google-iam-v1
diff --git a/packages/google-cloud-gke-connect-gateway/.flake8 b/packages/google-cloud-gke-connect-gateway/.flake8
index 87f6e408c47d..32986c79287a 100644
--- a/packages/google-cloud-gke-connect-gateway/.flake8
+++ b/packages/google-cloud-gke-connect-gateway/.flake8
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-connect-gateway/CONTRIBUTING.rst b/packages/google-cloud-gke-connect-gateway/CONTRIBUTING.rst
index 2db5522328b7..a00ceba157d4 100644
--- a/packages/google-cloud-gke-connect-gateway/CONTRIBUTING.rst
+++ b/packages/google-cloud-gke-connect-gateway/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.12 -- -k
+ $ nox -s unit-3.13 -- -k
.. note::
@@ -143,12 +143,12 @@ Running System Tests
$ nox -s system
# Run a single system test
- $ nox -s system-3.12 -- -k
+ $ nox -s system-3.13 -- -k
.. note::
- System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12.
+ System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13.
For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
@@ -227,6 +227,7 @@ We support:
- `Python 3.10`_
- `Python 3.11`_
- `Python 3.12`_
+- `Python 3.13`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
@@ -234,6 +235,7 @@ We support:
.. _Python 3.10: https://docs.python.org/3.10/
.. _Python 3.11: https://docs.python.org/3.11/
.. _Python 3.12: https://docs.python.org/3.12/
+.. _Python 3.13: https://docs.python.org/3.13/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/packages/google-cloud-gke-connect-gateway/MANIFEST.in b/packages/google-cloud-gke-connect-gateway/MANIFEST.in
index e0a66705318e..d6814cd60037 100644
--- a/packages/google-cloud-gke-connect-gateway/MANIFEST.in
+++ b/packages/google-cloud-gke-connect-gateway/MANIFEST.in
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-connect-gateway/docs/conf.py b/packages/google-cloud-gke-connect-gateway/docs/conf.py
index 27e6acac0d66..471d4e6d6a8c 100644
--- a/packages/google-cloud-gke-connect-gateway/docs/conf.py
+++ b/packages/google-cloud-gke-connect-gateway/docs/conf.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1/services/gateway_control/transports/rest.py b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1/services/gateway_control/transports/rest.py
index e67511c93645..e914cef437ee 100644
--- a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1/services/gateway_control/transports/rest.py
+++ b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1/services/gateway_control/transports/rest.py
@@ -41,7 +41,7 @@
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
- rest_version=requests_version,
+ rest_version=f"requests@{requests_version}",
)
diff --git a/packages/google-cloud-gke-connect-gateway/noxfile.py b/packages/google-cloud-gke-connect-gateway/noxfile.py
index 67b7265f7586..a9ceef47133c 100644
--- a/packages/google-cloud-gke-connect-gateway/noxfile.py
+++ b/packages/google-cloud-gke-connect-gateway/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -35,7 +35,15 @@
DEFAULT_PYTHON_VERSION = "3.10"
-UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -49,7 +57,7 @@
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"]
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"mock",
"pytest",
@@ -168,7 +176,7 @@ def install_unittest_dependencies(session, *constraints):
def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
constraints_path = str(
@@ -368,7 +376,7 @@ def docfx(session):
)
-@nox.session(python="3.12")
+@nox.session(python="3.13")
@nox.parametrize(
"protobuf_implementation",
["python", "upb", "cpp"],
@@ -376,7 +384,7 @@ def docfx(session):
def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
- if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"):
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
session.skip("cpp implementation is not supported in python 3.11+")
# Install all dependencies
diff --git a/packages/google-cloud-gke-connect-gateway/scripts/decrypt-secrets.sh b/packages/google-cloud-gke-connect-gateway/scripts/decrypt-secrets.sh
index 0018b421ddf8..120b0ddc4364 100755
--- a/packages/google-cloud-gke-connect-gateway/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-gke-connect-gateway/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC 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.
diff --git a/packages/google-cloud-gke-connect-gateway/setup.py b/packages/google-cloud-gke-connect-gateway/setup.py
index 9313d880df15..95129afcdca1 100644
--- a/packages/google-cloud-gke-connect-gateway/setup.py
+++ b/packages/google-cloud-gke-connect-gateway/setup.py
@@ -46,6 +46,7 @@
# See https://github.com/googleapis/google-cloud-python/issues/12364
"google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0",
"proto-plus >= 1.22.3, <2.0.0dev",
+ "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'",
"protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
extras = {}
@@ -84,6 +85,7 @@
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
"Topic :: Internet",
],
diff --git a/packages/google-cloud-gke-connect-gateway/testing/constraints-3.13.txt b/packages/google-cloud-gke-connect-gateway/testing/constraints-3.13.txt
new file mode 100644
index 000000000000..ed7f9aed2559
--- /dev/null
+++ b/packages/google-cloud-gke-connect-gateway/testing/constraints-3.13.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf